0% found this document useful (0 votes)
96 views33 pages

Javascript Javascript: Week 6 7

This document provides an agenda and overview of topics to be covered related to JavaScript in weeks 6-7. The topics include: client-side scripting, what JavaScript is and what it can do, where to place JavaScript code in HTML, writing output to HTML, JavaScript functions, reacting to events, changing HTML styles, form validation, and regular expressions. An example is given of updating HTML content by getting an element and changing its innerHTML when a button is clicked.

Uploaded by

splokbov
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views33 pages

Javascript Javascript: Week 6 7

This document provides an agenda and overview of topics to be covered related to JavaScript in weeks 6-7. The topics include: client-side scripting, what JavaScript is and what it can do, where to place JavaScript code in HTML, writing output to HTML, JavaScript functions, reacting to events, changing HTML styles, form validation, and regular expressions. An example is given of updating HTML content by getting an element and changing its innerHTML when a button is clicked.

Uploaded by

splokbov
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Javascript

Week 6‐7

Agenda
• Client‐side scripting
• What is JS
• What can we do with it?
• Wh
Where to put the JS?
t t th JS?
• Writing into HTML Output
• JS Functions
JS Functions
• Reacting to Events
• Changing HTML Styles
• Validation on Forms
• JS Regular Expressions

2
Web Programming
Web Programming
• Web Programming made up of:
g g p
– Static pages
– Server Side programming only
– Client and Server side programming
– AJAX
• So far, we have seen:
So far we have seen:
– Static
• HTML, Frames & Forms
• CSS

Client‐Side
Client Side Scripting
Scripting
• Client
Client‐side
side scripts are used mostly to:
scripts are used mostly to:
– used to write content to a page at the client
– used to validate form contents
– used to change the appearance and style of 
different objects
• Examples:
– Javascript
– vbscript
– Jscript

4
What is JS?
What is JS?
• JavaScript is a Scripting Language
• A scripting language is a lightweight programming 
language.
• JavaScript is programming code that can be inserted 
JavaScript is programming code that can be inserted
into HTML pages.
• JavaScript inserted into HTML pages, can be executed 
b ll
by all modern web browsers. 
d bb
• JavaScript statements are "commands" to the browser. 
The purpose of the statements is to tell the browser 
p p
what to do.
• NOTE : JS is case‐sensitive; name is not same as Name

What can a JavaScript do?

• JavaScript
JavaScript gives HTML designers a programming 
gives HTML designers a programming
tool ‐ put small "snippets" of code into their HTML 
pages
• JavaScript can put dynamic text into an HTML page 
– document.write("<h1>" + name + "</h1>“)
• JavaScript can react to events – onload, onclick
• JavaScript can be used to validate data ‐ A JavaScript 
can be used to validate form data before it is 
submitted to a server. 

6
What can a JavaScript do?

• JavaScrip pt can read and write HTML elements ‐ read 


and change the content of an HTML element
• JavaScript can be used to detect the visitor's 
b
browser ‐ A JavaScript can be used to detect the 
b d d h
visitor's browser, and ‐ depending on the browser ‐
load another page specifically designed for that
load another page specifically designed for that 
browser
• JavaScript can be used to create cookies ‐ A 
JavaScript can be used to store and retrieve 
information on the visitor's computer

Class Exercise
Class Exercise
• Give
Give one example where you might use JS to 
one example where you might use JS to
react on an event.
• Why is it important to validate form data 
Why is it important to validate form data
before it is submitted to a server?

8
Javascript – Where to put the script?
Javascript  Where to put the script?
Scripts to be executed when 
Scripts in either the body or 
Scripts in either the body or they are called or when an
they are called, or when an 
the head section or both: event is triggered, go in the 
head section
<html>
When we place a script in the 
<head> head section, we ensure that 
<script type="text/javascript"> the script is loaded before 
…some
some statements anyone uses it
anyone uses it
</script>
</head>
Scripts in the body will be 
Scripts in the body will be
<body>
executed immediately while 
<script type="text/javascript">
the page loads into the 
…some statements
browser 
</script>
</body>
This is not always what we 
want ! 9

Javascript – Where to put the script?
Javascript  Where to put the script?
External JavaScript file:
External JavaScript file:
– Sometimes you might want to run the same script on several pages, 
without writing the script on each and every page

– To simplify this, you can write a script in an external text file, and save 
it with “.js” extension
<html>

<head>
<script type="text/javascript“ src=“myScript.js"></script>
</head>

<body>

</body>
10
</html>
JavaScript Syntax
JavaScript Syntax
• Case Sensitive
Case Sensitive
• Add semicolon after each statement
– Good practice
G d ti
• Group JS statements using {……}

11

JavaScript Comments
JavaScript Comments
• Single line
g
//this statement is for writing hello world
document.write(“hello world”);
document.write(“how is the weather?”); // weather info

• Multi‐line
/* The statement below will output
h ll
hello world on the page */
ld th */
document.write(“hello world”);

12
JavaScript Variables
JavaScript Variables
• Hold values or expressions
Hold values or expressions
• Case sensitive (b & B are different variables)
• Should begin with a letter or underscore  _
Should begin with a letter or underscore

Egs:
var x;
var address;
var total = total +100;

13

Some JS Egs
Some JS Egs

14
JS Eg‐ Writing Into HTML Output
; seperates JS 
Statements

document.write( h1 This is a heading
document.write("<h1>This is a heading</h1>");
/h1 );
document.write("<p>This is a paragraph</p>");

This is a heading
This is a heading
This is a paragraph.

15

JS Eg ‐ Reacting to Events

<button type=
<button type="button"
button   
onclick="alert('Welcome!')">Click Me!</button>

Click Me!

Welcome

Ok

16
Functions
function functionname(var1,var2,...,varX)
{
some code

function functionname(var1,var2,...,varX)
functionname(var1 var2 varX)
{
some code
return val
}

17

JS Eg – Changing HTML Content
<html>
<ht l>
When called myFunction will overwrite the 
<head>
content of section demo
<script>
function myFunction()
function myFunction()
{
x=document.getElementById("demo");  // Find the  {} determines 
element scope of the JS 
Function
x.innerHTML="Hello JavaScript!";    // Change the 
content
}
</script>
</head>
Current text in section demo
<p id="demo">
id "d "
JavaScript can change the content of an HTML element.
</p> Calling function myFunction when 
clicking on button Click Me!
<button type="button" onclick="myFunction()">Click 
Me!</button> 18
…....
Class Exercise
Class Exercise
• Update
Update the previous example such that when  
the previous example such that when
you click on the button, the content of section 
demo is replaced with a level 1 heading
demo is replaced with a level 1 heading, 
Content

19

Answer
…..
<script>
function myFunction()
function myFunction()
{
x=document.getElementById("demo");  
g y ( );
x.innerHTML=" <h1>Content</h1>";   
}
</script>

……

20
JS Eg: Changing HTML Styles
….

<script>
This is a comment. For 
function myFunction()
y ()
multiple lines use /* */
multiple lines use /*….*/
{
//changing HTML styles. 
x=document.getElementById("demo") // Find the element
x.style.color="#ff0000";          // Change the style
}
</script> Changing HTML Style

<button type="button" onclick="myFunction()">Click Me!</button>

21

JS Eg – Validate Input
JS Eg  Validate Input
…..

<script>
function myFunction()
{
var x=document.getElementById("demo").value;
if(x==""||isNaN(x))
{
alert("Not
alert( Not Numeric
Numeric");
);
}
}
Output Error message if blank / non 
</script>
numeric
…….
<input id="demo" type="text">

<button type="button" onclick="myFunction()">Click Me!</button>
yp y () /
……..

22
JS – Form Validation
<!DOCTYPE html> <body>
body
<html> <form name="myForm"
<head> action="demo_form.asp"
<script> onsubmit="return validateForm()"
method="post">
function validateForm()
{ First name: <input type="text"
var  name="fname">
"f "
x=document.forms["myForm"]["fname
"].value; <input type="submit"
if (
if (x==null || x=="")
ll || "") value= Submit >
value="Submit">
{ </form>
</body> </html>
alert("First name must be filled out");
return false;
}
}
</script> </head>
23

Exercise – What is the importance of 
the codes in RED?
the codes in RED?
<script type="text/javascript"> <script >
<!‐‐ function myFunction()
y ()
f
function myFunction()
i i ()
{ {
var var
x=document.getElementById("d
d t tEl tB Id("d x=document getElement
x=document.getElement
emo").value; ById("demo").value;
if(x==""||isNaN(x)) if(x==""||isNaN(x))
{
alert("Not Numeric"); {
} alert("Not Numeric");
} }
}
‐‐>
</script>
/ i t
</script>
24
More on JS
More on JS
• Let
Let’ss get into the different building blocks
get into the different building blocks

25

JS Arithmetic Operators
JS Arithmetic Operators

26
Joining two or more strings
Joining two or more strings

txt1="What a very";
1 "Wh "
txt2="nice day";
txt3=txt1+txt2; 

• Adding a string and a number yields a string!
X=5+ “5”
document.write(X);

27

Comparison Operators
Comparison Operators
Given that x=5

28
Logical Operators
Logical Operators

29

Conditional Operator
Conditional Operator
VariableName=(condition)?value1:value2
drink=(time==“6am”)? “tea” : “juice”;

• If it is 6am, we drink tea; Else we drink juice!

30
Conditional Statement
Conditional Statement
if statement
f
if(condition)
{
code to be executed if condition is true
}

if(time==“8am”)
if(time== 8am )
{
d i k “ ff ”
drink=“coffee”;
} 31

Conditional Statement
Conditional Statement
if…else statement
if( di i )
if(condition) if(time==“8am”)
{ {
code to be executed if 
code to be executed if
condition is true
drink=“coffee”;
} }
else else
{ {
code to executed if  d k “
drink=“juice”;

condition is false }
}
32
Conditional Statement
Conditional Statement
if…else if…else statement
if(time==“8am”)
if(condition1)
{
{ drink=“coffee”;
code to be executed if condition1 is  }
true
else if(time==“11am”)
}
{
else if(condition2)
drink “j ice”
drink=“juice”;
{
}
code to executed if condition2 is true
else
}
{
else
drink=“water”;
{
}
code to be executed if both condition1 
and condition2 are false
33
}

Conditional statement
Conditional statement
<script type="text/javascript">
var d = new Date()
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else
{
d
document.write("<b>Hello World!</b>");
t it ("<b>H ll W ld!</b>")
}
</script>  34
Switch Statement (Case)
Switch Statement (Case)
switch(n)
( )
{
case 1:
execute code block 1
break;
case 2:
case 2:
execute code block 2
break;;
default:
code to be executed if n is different from case 1 and 
2
}  35

Switch example
Switch example
<script type="text/javascript">
/*You will receive a different greeting based
on what day it is. Note that Sunday=0,
M d 1 T d 2 t */
Monday=1, Tuesday=2, etc. */
var d=new Date();
theDay=d.getDay();
switch (theDay)
it h (th D )
{
case 5:
document.write("Finally Friday");
b k
break;
case 6:
document.write("Super Saturday");
break;
case 0:0
document.write("Sleepy Sunday");
break;
default:
d
document.write("I'm looking forward to this weekend!");
t it ("I' l ki f d t thi k d!")
}
</script>  36
Exercise Switch
• Write js codes to retrieve the current time and display the 
hours only and the following message.
• 10 – It’s … o’clock. Class time
• 12 – It’s … o’clock. Lunch time
• 13 – It’s … o’clock. Class time
’ ’l k l
• 16 – It’s … o’clock. Time to go home
• E.g if it
E g if it’ss 10:15, the message displayed should be:
10:15 the message displayed should be:
– It’s 10 o’clock. Class time

• Hint the getHours() method of the Date() class returns the 
hours

37

Answer
<script type="text/javascript">
//Hour only will be displayed
();
var d=new Date();
theTime=d.getHours();
switch (theTime)
{
case 10:
document.write(“It’s ” + theTime + “o’clock. Class time ");
break;
case 12:
(
document.write(“It’s ” + theTime + “o’clock. Lunch time ");
);
break;
case 13:
document.write(“It’s ” + theTime + “o’clock. Class time ");
break;;
case 16:
document.write(“It’s ” + theTime + “o’clock. Time to go home");
break;
default:
document.write(“No message for this hour!");
}
</script>  38
Popup Boxes: alert
Popup Boxes: alert

alert("I am an alert box!"); 

39

Popup Boxes: confirm


Popup Boxes: confirm
var r=confirm("Press a button!");
( );
if (r==true)
{
alert("You pressed OK!");
}
else
{
alert("You pressed Cancel!");
}
40
Popup Boxes: prompt
Popup Boxes: prompt

var name=prompt("Please enter your name","Harry Potter");

41

Functions
<body>
<html>
<form>
<head>
h d
<input type="button" 
<script type="text/javascript">
value="Click me!" 
function displaymessage()
function displaymessage()
onclick="displaymessage()" />
{
</form>
alert("Hello World!");
</body>
</body> 
}
</html>
</script>
</head> 
/h d

42
Functions: return
Functions: return
<head>
<script type="text/javascript">
i " /j i "
function product(a,b)
{
return a*b;
}
</script>
/ p
</head>
<body>
body
<script type="text/javascript">
document.write(product(4,3));
</script> </body>
</script> </body>
43

For Loop
For Loop
for 
(
(var=startvalue;var<=endvalue;var=
l d l
var+increment)
{
code to be executed

var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
( );
document.write("<br />");
}  44
While Loop
While Loop
while (var<=endvalue)
{
code to be executed

var ii=0;
0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}  45

Do While Loop
Do While Loop
var i=0;
do d
do
{ {
code to be
code to be  document write("The
document.write( The number is 
number is " + 
+
executed i);
}
while
while  document.write("<br
( //>");
);
(var<=endvalue);  i++;
}
while (i<=5); 

46
Break Statement
Break Statement
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
if (i==3)
{
break;
}
document.write("The number is " + i);
document write("<br
document.write( <br />
/>");
);

47

E
Exercise ‐
i L
Loops
• Write
Write a js function (Even(val)) which checks a 
a js function (Even(val)) which checks a
value input by the user on the current page 
(id: txt value) and displays even numbers up
(id: txt_value) and displays even numbers up 
to and/or including this value. E.g if the value 
input is 11 the following should be displayed:
input is 11, the following should be displayed:
• Even numbers are: 2, 4, 6, 8, 10.

48
Exercise – Loops Ans
Exercise  Loops Ans
function Even(val)
{
var i=0;
var str = “”;
f (i 1 i
for (i=1;i<=val;i++)
li )
{
if ((i%2)==0)
{
str = str+i+”,”
}
}
document.write(" Even numbers are: " + str);
}

49

Exercise – Loops Cont
Exercise  Loops Cont’d
d

• Write appropriate piece of code so that the 
p y
even numbers are displayed on click after 
txt_value has been enterd

50
Exercise – Loops Cont
Exercise  Loops Cont’d
d Ans
Ans

• Write appropriate piece of code so that the 
p y
even numbers are displayed on click after 
txt_value has been enterd

<input type="text" size="30" id=“txt_value” 
onchange=“Even(this.value);"> 

51

For In Statements
For In Statements

var x;
for (variable in object) var mycars = new Array();
{ mycars[0] = "Saab";
mycars[0] =  Saab ;
code to be executed mycars[1] = "Volvo";
}}  mycars[2] = "BMW";

for (x in mycars)
{
document.write(mycars[x] + "<br
/>");

52
Events
•A mouse click 
A li k
•onclick
•A web page or an image loading
•A web page or an image loading 
•onload (onunload)
•Mousing over a hot spot on the web page
g p p g
•onmouseover 
•Selecting an input field in an HTML form 
•onfocus
•Submitting an HTML form 
•onsubmit
•A keystroke 
•onkeydown
onkeydown
53

Events‐ Egs
<input type="text" size="30" id="email" 
onchange="checkEmail()"> 

<form method=
<form method="post"
post  action=
action="xxx
xxx.htm
htm" onsubmit=
onsubmit="return
return 
checkForm()"> 

<a href="http://www.w3schools.com" onmouseover="alert('An 
onMouseOver event');return false"><img src="w3s.gif" 
alt="W3Schools" /></a> 

54
Class Exercise
Class Exercise
• Assuming that you have a form with text fields and upon 
submitting it does the following validations:
submitting it does the following validations:

– Define a function max() that takes two numbers as arguments 
and returns the largest of them. 
and returns the largest of them

– Write a function disp() that takes two arguments (x,y) and then 
calls function max(x,y) and displays the value returned by 
ll f ( ) dd l h l db
function max. Eg displays    ... is larger

– Write the whole html tags which makes use of the above 
functions to display the largest of two numbers.

55

Answer
<!DOCTYPE html>
<!DOCTYPE html> <script>
function max(x,y)
<html> {
<body> if(x>y){return x;}
else
l {{return
t y;}}
}
<p>Please input two 
numbers</p>
b / function display(x
display(x,y)
y)
{
var z=max(x,y);
<input id=
<input id="num1"
num1   document write(z+" is larger");
document.write(z+ larger );
type="text"> }
</script>
<input id="num2" 
type="text"> <button type="button"
onclick="display(num1.value,num2.val
ue)">Maximum</button>

</body>
56
</html>
Regular Expressions
• A regular expression is an object that describes
a pattern of characters.
• When you search in a text, you can use a
pattern to describe what you are searching for.
• A simple pattern can be one single character.
• A more complicated pattern can consist of
more characters, and can be used for parsing,
format checking,
checking substitution and more.
more
• Regular expressions are used to perform
powerful pattern‐matching
pattern matching and "search
search‐and‐
and
replace" functions on text. 57

Regular Expressions – Symbols


Regular Expressions 
//… / / Æ represents a pattern you want to match
represents a pattern you want to match
^    Ærepresents the start of a string
$    Æ represents the end of a string
[0‐ 9]    Æ represents any of the characters 0 – 9
+    Æ represents at least once
* Æ represents ZERO OR MORE
. Æ matches ANY character
[[a‐zA‐Z]   
] Æ represents any alphabet
p y p

58
Regular Expressions – Symbols
Regular Expressions –
Regular Expressions 
• If
If we omit the 
we omit the ^, we specify that we want the 
we specify that we want the
pattern, but not necessarily starting at the 
start of the string
start of the string
• If we omit the $, again we specify that we 
want to have the pattern within the string
want to have the pattern within the string, 
and not how it ends

59

Consider the following fundtion 
which uses Regular Expression
hi h R l E i
function validateNumeric(val,label)
{
var filter = /^([0‐9])+$/;
if (!filter test(val))
if (!filter.test(val))
{
alert('Please
alert( Please enter numeric characters for 
enter numeric characters for '++ label);
label);
return false;
}
return true;
}//end validateNumeric

60
Regular Expression ‐ Exercise
Regular Expression 
• Give some valid and invalid values for val
Give some valid and invalid values for val

61

Regular Expressions ‐ Exercises


Regular Expressions 
• Using regular expressions, write functions 
which can validate the following passwords:
– Starts with a letter followed by at least 1 digit (e.g 
r4452)
– Starts with a digits followed by any number of 
l
letters(e.g 4dtg)
( 4d )
– Starts and ends with a letter
– Consist of Capital letters only
– Consist of 3 chars only (letter or digits)

62
Regular Expressions ‐Ans
– Starts with a letter followed by at least 1 digit (e.g 
r4452) : 
var filter = /^ [a‐zA‐Z] ([0‐9])+/;
– Starts with a digits followed by any number of 
l
letters(e.g 4dtg)
( d )
var filter = /^[0‐9] [a‐zA‐Z]* /;
– Starts and ends with a letter
var filter = /^[a‐zA‐Z].*[a‐zA‐Z] $/;

63

Regular Expressions ‐Ans


Regular Expressions  Ans
– Consist of Capital letters only
Consist of Capital letters only
var filter = /^[A‐Z]+ $/;
– Consist of 3 chars only (letter or digits)
Consist of 3 chars only (letter or digits)
var filter = /^[0‐9a‐zA‐Z]{3}$/;

64
References
• CSE
CSE 1041 
1041 – Previous lecture notes
Previous lecture notes
• http://www.w3schools.com/js
• https://developer.mozilla.org/en‐
h //d l ill /
US/docs/JavaScript/Guide/Regular_Expression
s

65

You might also like