Chapter Three: Client-Side Scripting (Javascript)
Chapter Three: Client-Side Scripting (Javascript)
Chapter Three: Client-Side Scripting (Javascript)
Comments
// single line comment
/* multi line
comment */
6 Internet Programming
Literals (constants)
12 // The number twelve
1.2 // The number one point two
"hello world" // A string of text
'Hi' // Another string
true // A Boolean value
false // The other Boolean value
null // Absence of an object
7 Internet Programming
Identifiers
The first character must be a letter, an underscore (_), or a
dollar sign ($).
Subsequent characters can be a letter, a digit, an underscore, or
a dollar sign.
Examples
i
distance_value
v13 _dummy
$str
_some_variable
8 Internet Programming
Reserved words
9 Internet Programming
How to add JavaScript to an HTML page
use the <script> tag
in the <head> element
<head>
…
<script type=“text/javascript”>
… javascript code (functions)
</script>
or
<script type=“text/javascript” src=“js_file.js”></script>
</head>
10 Internet Programming
JavaScript (cont’d)
anywhere in the HTML document
…
<body>
…
<script type=“text/javascript”>
document.write(“hello”);
</script>
…
</body>
…
11 Internet Programming
The example below writes a <p> element with current
date information to the HTML document:
<html>
<body>
<h1>My First Web Page</h1>
<script type="text/javascript">
document.write("<p>" + Date() + "</p>");
</script>
</body>
</html>
12 Internet Programming
Changing HTML Elements
The example below writes the current date into an existing
<p> element:
Example
<html>
<body>
<h1>My First Web Page</h1>
<p id="demo"></p>
<script type="text/javascript">
document.getElementById("demo").innerHTML=Date();
</script>
</body>
13 Internet Programming
JavaScript in <head>
The example below calls a function when a button is
clicked:
Example
<html>
<head>
<script type="text/javascript">
function displayDate()
{
document.getElementById("demo").innerHTML=Date(
);
}14 Internet Programming
</script>
</head>
<body>
<h1>My First Web Page</h1>
<p id="demo"></p>
<button type="button" onclick="displayDate()">Display Date</button>
</body>
</html>
15 Internet Programming
Scripts in <head> and <body>
You can place an unlimited number of scripts in your
document, and you can have scripts in both the body and
the head section at the same time.
It is a common practice to put all functions in the head
section, or at the bottom of the page. This way they are all
in one place and do not interfere with page content.
16 Internet Programming
Using an External JavaScript
JavaScript can also be placed in external files.
External JavaScript files often contains code to be used on
several different web pages.
External JavaScript files have the file extension .js.
Note: External script cannot contain the <script></script>
tags!
To use an external script, point to the .js file in the "src"
attribute of the <script> tag:
17 Internet Programming
Example
<html>
<head>
<script type="text/javascript" src="xxx.js"></script>
</head>
<body>
</body>
</html>
18 Internet Programming
JavaScript Statements
JavaScript Statements
JavaScript is a sequence of statements to be executed by
the browser
JavaScript is Case Sensitive
Unlike HTML, JavaScript is case sensitive - therefore
watch your capitalization closely when you write
JavaScript statements, create or call variables, objects and
functions.
19 Internet Programming
A JavaScript statement is a command to a browser. The
purpose of the command is to tell the browser what to do.
This JavaScript statement tells the browser to write "Hello
Dolly" to the web page:
document.write("Hello Dolly");
It is normal to add a semicolon at the end of each
executable statement. Most people think this is a good
programming practice, and most often you will see this in
JavaScript examples on the web.
20 Internet Programming
The semicolon is optional (according to the JavaScript
standard), and the browser is supposed to interpret the end
of the line as the end of the statement. Because of this you
will often see examples without the semicolon at the end.
Note: Using semicolons makes it possible to write
multiple statements on one line.
21 Internet Programming
JavaScript (cont’d)
Datatypes and Variables
numbers
strings
boolean
objects
arrays
Variable Declaration
syntax:
var identifier [ = initial_value ]
ex. var x;
var first_name = ‘Abebe’;
22 Internet Programming
Operators
Arithmetic Operators
Operator Description Example Result
+ Addition x=2 4
y=2
x+y
- Subtraction x=5 3
y=2
x-y
* Multiplication x=5 20
y=4
x*y
/ Division 15/5 3
5/2 2.5
% Modulus (division remainder) 5%2 1
10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
23 Internet Programming
Operators (cont’d)
Assignment Operators
24 Internet Programming
Operators (cont’d)
Comparison Operators
25 Internet Programming
Operators (cont’d)
Logical Operators
26 Internet Programming
Control Statements
Conditional statements
if, if else
switch
looping
while
do … while
for
conditional operator
var_name = (condition) ? true_value : false_value
27 Internet Programming
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
28 Internet Programming
Break in a loop
Continue in a loop
JavaScript For...In Statement
The for...in statement loops through the properties of an
object.
Syntax:
for(varaible in object)
{
code to be executed
}
Note: The code in the body of the for...in loop is executed
29once for each property Internet Programming
Example:
var person={fname:"John",lname:"Doe",age:25};
for (x in person)
{
document.write(person[x] + " ");
}
30 Internet Programming
Functions
A function will be executed by an event or by a call to the
function
syntax:
function function_name( argument1, argument2, …){
statements
[return value]
}
calling:
[var_name = ] function_name(arg_list)
31 Internet Programming
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>
32 Internet Programming
The return Statement
The return statement is used to specify the value that is returned from the function
<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>
</body>
</html
33 Internet Programming
JavaScript Objects
Everything in JavaScript is an Object: a String, a Number, an Array, a
Function....
In addition, JavaScript allows you to define your own objects.
JavaScript has several built-in objects, like String, Date, Array, and more.
An object is just a special kind of data, with properties and methods.
objectName.propertyName
This example uses the length property of the String object to find the length
of a string:
var message="Hello World!";
var x=message.length;
34 Internet Programming
Accessing Objects Methods
Methods are the actions that can be performed on objects.
You can call a method with the following syntax:
objectName.methodName()
This example uses the toUpperCase() method of the String object, to
convert a text to uppercase:
var message="Hello world!";
var x=message.toUpperCase();
35 Internet Programming
JavaScript Strings
The String object is used for storing and manipulating text.
A string simply stores a series of characters like “Computer Science".
A string can be any text inside quotes. You can use simple or double quotes:
Syntax
var txt = new String(string);
or more simply:
var txt = string;
Example
var carname='Volvo XC60';
You can access each character in a string with its position (index):
Example
var character=carname[7];
String indexes are zero-based, which means the first character is [0], the second is [1], and so on.
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
Example
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
36 Internet Programming
String Length
The length of a string (a string object) is found in the built in property
length:
Example
var txt="Hello World!";
document.write(txt.length);
Finding a String in a String
The indexOf() method returns the position (as a number) of the first found
occurrence of a specified text inside a string:
Example
var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome");
The method returns -1 if the specified text is not found.
37 Internet Programming
Matching Content
The match() method can be used to search for a matching content in a
string
<!DOCTYPE html>
<html>
<body>
<script>
var str="Hello world!";
document.write(str.match("world") + "<br>"); // world
document.write(str.match("World") + "<br>"); //Null
document.write(str.match("world!")); // world!
</script>
</body>
</html>
38 Internet Programming
Replacing Content
The replace() method replaces a specified value with
another value in a string.
Example
str="Please visit Microsoft!"
var n=str.replace("Microsoft", "Google");
39 Internet Programming
Example
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "Microsoft" with "W3Schools" in the paragraph
below:</p>
<p id="demo">Please visit Microsoft!</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str=document.getElementById("demo").innerHTML;
var n=str.replace("Microsoft","W3Schools");
document.getElementById("demo").innerHTML=n;
} </script> </body> </html>
40 Internet Programming
Upper Case and Lower Case
A string is converted to upper/lower case with the
methods toUpperCase() / toLowerCase():
Example
var txt="Hello World!"; // String
var txt1=txt.toUpperCase(); // txt1 is txt converted to upper
var txt2=txt.toLowerCase(); // txt2 is txt converted to lower
41 Internet Programming
The + operator can also be used to add string variables or text
values together.
To add two or more string variables together, use the +
operator.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
42 Internet Programming
JavaScript Array Object
An array is a special variable, which can hold more than one
value at a time.
Create an Array
An array can be created in three ways.
The following code creates an Array object called myCars:
1: Regular:
var myCars=new Array();
myCars[0]=“Jeep";
myCars[1]="Volvo";
myCars[2]="BMW";
2: Condensed:
var myCars=new Array(“Jeep","Volvo","BMW");
3: Literal:
var myCars=[“Jeep","Volvo","BMW"];
43 Internet Programming
Access an Array
You refer to an element in an array by referring to the
index number.
This statement access the value of the first element in
myCars:
var name=myCars[0];
This statement modifies the first element in myCars:
myCars[0]="Opel";
44 Internet Programming
You Can Have Different Objects in One Array
All JavaScript variables are objects. Array elements are
objects. Functions are objects.
Because of this, you can have variables of different types
in the same Array.
You can have objects in an Array. You can have functions
in an Array. You can have arrays in an Array
myArray[0]=Date.now;
myArray[1]=myFunction;
myArray[2]=myCars;
45 Internet Programming
Array Methods and Properties
The Array object has predefined properties and methods:
var x=myCars.length // the number of elements in myCars
var y=myCars.indexOf("Volvo") // the index position of "Volvo"
46 Internet Programming
RegExp Object
A regular expression is an object that describes a pattern
of characters.
Regular expressions are used to perform pattern-
matching and search-and-replace functions on text.
Syntax
var patt = new RegExp(pattern,modifiers);
or more simply:
47 Internet Programming
pattern specifies the pattern of an expression
modifiers specify if a search should be global, case-
sensitive, etc.
Modifiers
Modifiers are used to perform case-insensitive and global searches:
Modifier Description
Perform a global match (find all matches rather than stopping after
g the first match)
m Perform multiline matching
48 Internet Programming
Example 1
Do a case-insensitive search for "w3schools" in a string:
<!DOCTYPE html>
<html>
<body>
<script>
var str = "Visit W3Schools";
var x = /w3schools/i;
document.write(str.match(x)); //W3Schools
</script>
</body>
</html
49 > Internet Programming
Example 2
Do a global search for "is":
50 Internet Programming
<!DOCTYPE html>
<html>
<body>
<script>
var str="Is this all there is?";
var patt1=/is/g;
document.write(str.match(patt1)); // is,is
</script>
</body>
</html>
51 Internet Programming
Brackets
Brackets are used to find a range of characters:
Expression Description
[abc] Find any character between the brackets
[^abc] Find any character not between the brackets
[0-9] Find any digit from 0 to 9
[A-Z] Find any character from uppercase A to uppercase Z
[a-z] Find any character from lowercase a to lowercase z
[a-Z] Find any character from uppercase A to lowercase z
(red|blue|green) Find any of the alternatives specified
52 Internet Programming
<!DOCTYPE html>
<html>
<body>
<script>
var str="Is this all there is?";
var patt1=/[a-h]/g;
document.write(str.match(patt1)); //h,a,h,e,e
</script>
</body>
</html>
53 Internet Programming
<!DOCTYPE html>
<html>
<body>
<script>
var str="THat's hoT!";
var patt1=/h.t/gi;
document.write(str.match(patt1)); //Hat, hoT
</script>
</body>
</html>
54 Internet Programming
The n+ quantifier matches any string that contains at least
one n.
Syntax
56 Internet Programming
57 Internet Programming
Confirm Box
A confirm box is often used if you want the user to verify
or accept something.
When a confirm box pops up, the user will have to click
either "OK" or "Cancel" to proceed
confirm(“Are you sure you want to delete the Internet?”)
58 Internet Programming
Prompt Box
A prompt box is often used if you want the user to input a
value before entering a page.
When a prompt box pops up, the user will have to click
either "OK" or "Cancel" to proceed after entering an input
value.
If the user clicks "OK" the box returns the input value. If
the user clicks "Cancel" the box returns null.
59 Internet Programming
promt(“You seems to be new user. Please enter your full
name to use chat group”)
60 Internet Programming
Events
Events are actions that can be detected by JavaScript.
A JavaScript can be executed when an event occurs, like
when a user clicks on an HTML element
Every element on a web page has certain events which can
trigger a JavaScript. For example, we can use the onClick
event of a button element to indicate that a function will
run when a user clicks on the button.
We define the events in the HTML tags.
61 Internet Programming
Examples of events:
When a user clicks the mouse
When a web page has loaded
When an image has been loaded
When the mouse moves over an element
When an input field is changed
When an HTML form is submitted
When a user strokes a key
Note: Events are normally used in combination with functions, and the function
will not be executed before the event occurs!
<!DOCTYPE html>
<html>
<body>
<h1 onclick="this.innerHTML=‘I am a JavaScript Event!’ ">Click on this text!</h1>
</body>
</html>
62 Internet Programming
onLoad and onUnload
The onLoad and onUnload events are triggered when the
user enters or leaves the page.
The onLoad event is often used to check the visitor's
browser type and browser version, and load the proper
version of the web page based on the information.
The onchange Event
The onchange event are often used in combination with
validation of input fields.
<input type="text" size="30" id="email"
onchange="checkEmail()">
63
Internet Programming
onFocus
User just moved into this form element.
onBlur:
A form field lost the focus (User moved to another field
onSubmit
The onSubmit event is used to validate ALL form fields
before submitting it
<form name=“myForm” method="post" action="xxx.htm"
onsubmit="return checkForm()">
onmouseover : A mouse moved on this element
onmouseout : The mouse moved out from this element.
64 Internet Programming
JavaScript Form Validation
JavaScript provides a way to validate form's data on the
client's computer before sending it to the web server.
Form validation generally performs two functions.
Basic Validation - First of all, the form must be
checked to make sure all the mandatory fields are filled in.
It would require just a loop through each field in the form
and check for data.
Data Format Validation - Secondly, the data that is
entered must be checked for correct form and value. Your
code must include appropriate logic to test correctness of
data.
65 Internet Programming
Form validation Example
66 Internet Programming
<html><head>
<script type="text/javascript">
var mess="";
function validate()
{ validateuserid();
validateusername()
validatecountry();
validatezipcode();
validateemail();
validategender();
validatelangauge();
validatedescription();
if(mess.length==0)
return true;
67 Internet Programming
else
{
alert(mess);
mess="";
return false;
}
68 Internet Programming
function validateuserid()
{
var uid=document.regform.userid.value;
//var uid=document.getElementById("userid").value;
var len=uid.length;
if(len==0 || len < 5 || len > 12)
{
alert("User id must be between 5 and 12 \n“);
document.regform.userid.focus();
}
}
69 Internet Programming
function validateusername()
{
var uname=document.regform.username.value;
//var uname=document.getElementById("username").value;
//var uname=regform.username.value;
var pattern=/^[a-zA-Z0-9]+/;
//if(uname.match(pattern))
if(uname.search(pattern) ==-1)
{
mess = mess + "User name should conatin only alphanumeric characters \n";
}
}
70 Internet Programming
function validatecountry()
{
var country=document.regform.country.value;
if(country=="Default")
{
mess = mess + "Please select Your country \n";
}
}
71 Internet Programming
function validatezipcode(){
var zipcode=document.regform.zip.value;
var pattern=/^[a-zA-Z]+$/;
if(zipcode.search(pattern)==-1)
{
mess = mess + "Zip code must contain only numberic
characters \n";
}
}
72 Internet Programming
function validateemail()
{
var email=document.regform.email.value;
var mailformat = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$ /;
if(email.match(mailformat))
{
// return true;
}
else
{
mess = mess + "Mail is not in correct format";
}
}
73 Internet Programming
function validategender()
{ var gender=document.regform. gender;
var i;
var ischecked=0;
for(i=0;i<gender.length;i++)
{
if(gender[i].checked)
{
ischecked=1;
break;
} }
if(ischecked==0)
mess=mess+"Oh! PLease select your gender \n"; }
74 Internet Programming
function validatelangauge()
{
//var langauges = [regform.en,regform.nonen]; //OR
var langauges = new Array(regform.en,regform.nonen);
var i;
var ischecked=0;
for(i=0;i<langauges.length;i++)
{
if(langauges[i].checked){
ischecked=1;
break;
} }
//alert("Langauge is not chekecked!!!");
//return false;
if(ischecked==0)
mess=mess + "Langauge is not chekecked!!! \n";
} 75 Internet Programming
function validatedescription()
{
var desc=regform.desc.value;
var len=desc.length;
if(len==0)
{
mess= mess + "This is a required field \n";
}
76 Internet Programming