Web Programming Unit-2
Web Programming Unit-2
• Contains only 'A' – 'Z', 'a' – 'z', '0' – '9', '_', '$'
• First character cannot be a digit
• Case-sensitive
• Cannot be reserved words or keywords
Variable and Variable Declaration
<head><script type="text/javascript">
// We are in the default scope – the "window" object.
x = 3; // same as "window.x = 3"
var y = 4; // same as "y = 4" or "window.y = 4"
</script></head>
• Post/pre increment/decrement
– ++, --
• Comparison operators
– ==, !=, >, >=, <, <=
– ===, !== (Strictly equals and strictly not equals)
• i.e., Type and value of operand must match / must not
match
== vs ===
// Type conversion is performed before comparison
var v1 = ("5" == 5); // true
• || – Logical OR
– OP1 || OP2
– If OP1 is true, expression evaluates to the value of OP1.
Otherwise the expression evaluates to the value of OP2.
var tmp1 = null && 1000; // tmp1 is null
• Assignment operators
– =, +=, -=, *=, /=, %=
• Bitwise operators
– &, |, ^, >>, <<, >>>
Conditional Statements
• “if” statement
• “if … else” statement
• "? :" ternary conditional statement
• “switch” statement
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Conditional Statements Examples
<script>
x=3
if(x<0)
{
alert (“negatif”)
}
else
{
alert (“pozitif”)
}
</script>
Conditional Statements Examples - 2
<script>
c=confirm(“Kitap Okuyor musunuz?”)
if(c)
{
alert (“tebrikler walla”)
}
else
{
alert (“ayıp ettiniz ama”)
}
</script>
Conditional Statements Examples - 3
<script>
p=prompt("Ankara'nın plaka numarası nedir?", " ")
if(p=="06")
{
alert("Doğru")
}
else
{
alert("Yanlış")
}
</script>
Built-In Functions
• eval(expr)
– evaluates an expression or statement
• eval("3 + 4"); // Returns 7 (Number)
• eval("alert('Hello')"); // Calls the function alert('Hello')
• isFinite(x)
– Determines if a number is finite
• isNaN(x)
– Determines whether a value is “Not a Number”
Built-In Functions
• parseInt(s)
• parseInt(s, radix)
– Converts string literals to integers
– Parses up to any character that is not part of a valid integer
• parseInt("3 chances") // returns 3
• parseInt(" 5 alive") // returns 5
• parseInt("How are you") // returns NaN
• parseInt("17", 8) // returns 15
• parseFloat(s)
– Finds a floating-point value at the beginning of a string.
• parseFloat("3e-1 xyz") // returns 0.3
• parseFloat("13.5 abc") // returns 13.5
Events
• An event occurs as a result of some activity
– e.g.:
• A user clicks on a link in a page
• Page finished loaded
• Mouse cursor enter an area
• A preset amount of time elapses
• A form is being submitted
Event Handlers
• Event Handler – a segment of codes (usually a
function) to be executed when an event
occurs
• When the mouse cursor is over the link, the browser displays the text "CUHK
Home" instead of the URL.
• The "return true;" of onMouseOver forces browser not to display the URL.
• window.status and window.defaultStatus are disabled in Firefox.
onSubmit Event Handler Example
<html><head>
<title>onSubmit Event Handler Example</title>
<script type="text/javascript">
function validate() {
// If everything is ok, return true
// Otherwise return false
}
</script>
</head>
<body>
<form action="MessageBoard" method="POST"
onSubmit="return validate();"
>
…
</form></body></html>
• See online references for complete list of available methods in these objects:
http://javascript-reference.info/
String Object (Some useful methods)
• length
–A string property that tells the number of character in the string
• charAt(idx)
–Returns the character at location "idx"
• toUpperCase(), toLowerCase()
–Returns the same string with all uppercase/lowercase letters
• substring(beginIdx)
–Returns a substring started at location "beginIdx"
• substring(beginIdx, endIdx)
–Returns a substring started at "beginIdx" until "endIdx" (but
not including "endIdx"
• indexOf(str)
–Returns the position where "str" first occurs in the string
Error and Exception Handling in JavaScript
• Javascript makes no distinction between Error
and Exception (Unlike Java)
• Handling Exceptions
– The onError event handler
• A method associated with the window object.
• It is called whenever an exception occurs
– The try … catch … finally block
• Similar to Java try … catch … finally block
• For handling exceptions in a code segment
– Use throw statement to throw an exception
• You can throw value of any type
– The Error object
• Default object for representing an exception
• Each Error object has a name and message properties
How to use “onError” event handler?
<html>
<head>
<title>onerror event handler example</title>
<script type="text/javascript">
function errorHandler(){
alert("Error Ourred!");
}
// JavaScript is casesensitive
// Don't write onerror!
window.onError = errorHandler;
</script>
</head>
<body>
<script type="text/javascript">
document.write("Hello there;
</script>
</body>
</html>
try … catch … finally
try {
// Contains normal codes that might throw an exception.
} catch ( errorVariable ) {
// Codes here get executed if an exception is thrown
// in the try block.
} finally {
// Executed after the catch or try block finish
} catch( errVar ) {
document.write("Exception caught<br>");
// errVar is an Error object
// All Error objects have a name and message properties
document.write("Error name: " + errVar.name + "<br>");
document.write("Error message: " + errVar.message +
"<br>");
} finally {
document.write("Finally block reached!");
}
</script>
Throwing Exception
<script type="text/javascript">
try{
var num = prompt("Enter a number (1-2):", "1");
// You can throw exception of any type
if (num == "1")
throw "Some Error Message";
else
if (num == "2")
throw 123;
else
throw new Error ("Invalid input");
} catch( err ) {
alert(typeof(errMsg) + "\n" + err);
// instanceof operator checks if err is an Error object
if (err instanceof Error)
alert("Error Message: " + err.message);
}
</script>
Document Object Model (DOM)
• When a web page is loaded, the browser
creates a Document Object Model of the page.
• Representation of the current web page as a
tree of Javascript objects
• allows you to view/modify page elements in
script code after page has loaded
• client side = highly responsive interactions
• browser-independent
• allows progressive enhancement.
• With the object model, JavaScript gets all the power it
needs to create dynamic HTML:
• JavaScript can change all the HTML elements in the
page
• JavaScript can change all the HTML attributes in the
page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and
attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the
page
• JavaScript can create new HTML events in the page
What is the DOM?
• ObjectProperties
1.car.name = Fiat 2.car.model = 500
3.car.weight = 850kg 4.car.color = white
• Methods
1.car.start() 2.car.drive()
3.car.brake() 4.car.stop()
• All cars have the same properties, but the
property values differ from car to car.
• All cars have the same methods, but the
methods are performed at different times.
• JavaScript Objects
• You have already learned that JavaScript
variables are containers for data values.
• This code assigns a simple value (Fiat) to
a variable named car:
• <!DOCTYPE html>
• <html>
• <body>
• <p>Creating a JavaScript Variable.</p>
• <p id="demo"></p>
• <script>
• var car = "Fiat";
• document.getElementById("demo").innerHTML =
car;
• </script>
• </body>
• </html>
• Objects are variables too. But objects can contain many values.
• This code assigns many values (Fiat, 500, white) to a variable named
car:
• <!DOCTYPE html>
• <html>
• <body>
• <p>Creating a JavaScript Object.</p>
• <p id="demo"></p>
• <script>
• var car = {type:"Fiat", model:"500", color:"white"};
• document.getElementById("demo").innerHTML = car.type;
• </script>
• </body>
• </html>
• <p id="demo"></p>
• <script>
• var person = {
• firstName: "John",
• lastName : "Doe",
• id : 5566
• };
• document.getElementById("demo").innerHTML =
• person.firstName + " " + person.lastName;
• </script>
• </body>
• </html>
• <!DOCTYPE html>
• <html>
• <body>
• <p>
• There are two different ways to access an object property:
• </p>
• <p>You can use person.property or person["property"].</p>
• <p id="demo"></p>
• <script>
• var person = {
• firstName: "John",
• lastName : "Doe",
• id : 5566
• };
• document.getElementById("demo").innerHTML =
• person["firstName"] + " " + person["lastName"];
• </script>
• </body>
• </html>
Accessing Object Methods
• <p id="demo"></p>
• <script>
• var person = {
• firstName: "John",
• lastName : "Doe",
• id : 5566,
• fullName : function() {
• return this.firstName + " " + this.lastName;
• }
• };
• document.getElementById("demo").innerHTML = person.fullName();
• </script>
• </body>
• </html>
The Form Object
• Two aspects of the form can be manipulated through
JavaScript. First, most commonly and probably most
usefully, the data that is entered onto your form can be
checked at submission. Second you can actually build
forms through JavaScript.
• Form object supports three events to validate the form
onClick = “method()”
• This can be applied to all form elements. This event is
triggered when the user clicks on the element.
onSubmit = “method()”
• This event can only be triggered by form itself and occurs
when a form is submitted.
onReset = “method()”
• This event can only be triggered by form itself and occurs
when a form is reset.
The browser Object
• The browser is JavaScript object that can be
used to know the details of browser. Some of
the properties of the browser object is as
follows:
Property Description
navigator.appCodeName It returns the internal name for the
browser. For major browsers it is Mozilla
navigator.appName It returns the public name of the browser –
navigator or
Internet Explorer
navigator.appVersion It returns the version number, platform
on which the browser is running.
navigator.userAgent The strings appCodeName and appVersion
concatenated
together
navigator.plugins An array containing details of all installed
plug-ins
Navigator.mimeTypes An array of all supported MIME Types
The Math Object
Displaying Arrays
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>
</body>
</html> 76
Creating an Array Cont..
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array-name = [item1, item2, ...];
Using the JavaScript Keyword new
The following example also creates an Array, and assigns values to it:
var cars = new Array("Saab", "Volvo", "BMW");
Access the Elements of an Array
You refer to an array element by referring to the index number.
var name = cars[0];
This statement modifies the first element in cars:
cars[0] = "Opel";
Can Have Different Objects in One Array
• JavaScript variables can be objects. Arrays are special kinds
of objects.
• Because of this, you can have variables of different types in
the same Array.
Example:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars; 77
Cont..
Arrays are Objects
• Arrays are a special type of objects. The typeof operator in
JavaScript returns "object" for arrays.
• But, JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this example,
person[0] returns John:
Array: var person = ["John", "Doe", 46];
Objects use names to access its "members". In this example,
person.firstName returns John:
Object: var person = {firstName:"John", lastName:"Doe“,
age:46};
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array
properties and methods:
Examples
var x = cars.length; // The length property returns the number
of elements in cars
var y = cars.sort(); // The sort() method sort cars in
alphabetical order
78
Cont..
Note:
❖ var points = new Array(); // Bad
❖ var points = []; // Good
79
Array Object Methods Cont..
Method Description
concat() Joins two or more arrays, and returns a copy of the joined arrays
indexOf() Search the array for an element and returns its position
join() Joins all elements of an array into a string
Search the array for an element, starting at the end, and returns
lastIndexOf()
its position
pop() Removes the last element of an array, and returns that element
Adds new elements to the end of an array, and returns the new
push()
length
reverse() Reverses the order of the elements in an array
shift() Removes the first element of an array, and returns that element
arr.indexOf(1);
83
JavaScript Regular Expressions
• A regular expression is a sequence of characters that forms
a search pattern.
• The search pattern can be used for text search and text
replace operations.
Syntax
/pattern/modifiers;
Example:
var patt = /w3schools/I
84
Cont..
Using String Methods
In JavaScript, regular expressions are often used with the
two string methods: search() and replace().
❖ The search(pattern) method uses an expression to search for a
match, and returns the position of the match.
❖ The replace(pattern1, pattern2) method returns a modified
string where the pattern is replaced.
❖ The split(pattern) method
❖ The match(pattern) method searches for a matching pattern.
Returns an array holding the results, or null if no match is found.
Example
var str = "Visit W3Schools";
var n = str.search(/w3schools/i);
The result in n will be: 6
Example
var str = "Visit Microsoft!";
var res = str.replace(/microsoft/i, "W3Schools");
The result in res will be: Visit W3Schools! 85
Cont..
Regular Expression Modifiers
Example
var patt = /e/;
patt.test("The best things in life are free!");
(or)
/e/.test("The best things in life are free!")
Since there is an "e" in the string, the output of the code above will
be: true
89
constructor
• It returns a reference to the array function that
created the instance's prototype.
• Syntax
• Its syntax is as follows:
RegExp.constructor
• Return Value
• Returns the function that created this object's
instance.
• Example
Try the following example program.
<html>
<head>
<title>JavaScript RegExp constructor Property</title>
</head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
document.write("re.constructor is:" + re.constructor);
</script>
</body>
</html>
Output
• re.constructor is:function RegExp() { [native code]
global
global is a read-only boolean property of RegExp
objects. It specifies whether a particular regular
expression performs global matching, i.e.,
whether it was created with the "g" attribute.
Syntax
Its syntax is as follows:
RegExpObject.global
Return Value
Returns "TRUE" if the "g" modifier is set, "FALSE"
otherwise.
<html>
<head>
<title>JavaScript RegExp global Property</title>
</head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
if ( re.global ){
document.write("Test1 - Global property is set");
}else{
document.write("Test1 - Global property is not set");
}
re = new RegExp( "string", "g" );
if ( re.global ){
document.write("<br />Test2 - Global property is set");
}else{
document.write("<br />Test2 - Global property is not set");
}
</script>
</body>
</html>
Output
Test1 - Global property is not set
Test2 - Global property is set
ignoreCase
ignoreCase is a read-only boolean property of
RegExp objects. It specifies whether a
particular regular expression performs case-
insensitive matching, i.e., whether it was
created with the "i" attribute.
• Syntax
Its syntax is as follows:
• RegExpObject.ignoreCase
• Return Value
Returns "TRUE" if the "i" modifier is set,
"FALSE" otherwise.
<html>
<head>
<title>JavaScript RegExp ignoreCase Property</title>
</head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
if ( re.ignoreCase ){
document.write("Test1 - ignoreCase property is set");
}else{
document.write("Test1 - ignoreCase property is not set");
}
re = new RegExp( "string", "i" );
if ( re.ignoreCase ){
document.write("<br />Test2 - ignoreCase property is set");
}else{
document.write("<br />Test2 - ignoreCase property is not set");
}
</script>
</body>
</html>
Output
Test1 - ignoreCase property is not set
Test2 - ignoreCase property is set
lastIndex
lastIndex is a read/write property of RegExp
objects. For regular expressions with the "g"
attribute set, it contains an integer that specifies
the character position immediately following the
last match found by the RegExp.exec() and
RegExp.test() methods. These methods use this
property as the starting point for the next search
they conduct.
This property is read/write, so you can set it at
any time to specify where in the target string,
the next search should begin. exec() and test()
automatically reset the lastIndex to 0 when
they fail to find a match (or another match).
Syntax
Its syntax is as follows:
RegExpObject.lastIndex
Return Value
Returns an integer that specifies the character
position immediately following the last match.
<html>
<head>
<title>JavaScript RegExp lastIndex Property</title>
</head>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
re.test(str);
document.write("Test 1 - Current Index: " + re.lastIndex);
re.test(str);
document.write("<br />Test 2 - Current Index: " + re.lastIndex);
</script>
</body>
</html>
Output
Test 1 - Current Index: 10
Test 2 - Current Index: 35
multiline
multiline is a read-only boolean property of
RegExp objects. It specifies whether a
particular regular expression performs
multiline matching, i.e., whether it was created
with the "m" attribute.
Syntax
Its syntax is as follows:
RegExpObject.multiline
Return Value
Returns "TRUE" if the "m" modifier is set, "FALSE"
otherwise.
<html>
<head>
<title>JavaScript RegExp multiline Property</title>
</head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
if ( re.multiline ){
document.write("Test1-multiline property is set");
}else{
document.write("Test1-multiline property is not set");
}
re = new RegExp( "string", "m" );
if ( re.multiline ){
document.write("<br/>Test2-multiline property is set");
}else{
document.write("<br/>Test2-multiline property is not
set");
}
</script>
</body>
</html>
Output
Test1-multiline property is not set
Test2-multiline property is set
Exception Handling
Try… Catch and Throw statements
Catching errors in JavaScript:
It is very important that the errors thrown must be catched or
trapped so that they can be handled more efficiently and
conveniently and the users can move better through the
web page.
Using try…catch statement:
The try..catch statement has two blocks in it:
· try block
· catch block
In the try block, the code contains a block of code that is to be
tested for errors.
The catch block contains the code that is to be executed if an
error occurs. The general syntax of try..catch statement is as
follows:
Exception Handling
throw
Example:
do something
if an error happens
{
create a new exception object
throw the exception
}
try……..
Example: try
{
statement one
statement two
statement three
}
catch
Example:
catch exception
{
handle the exception }
104
The concept of try…catch statement
<html>
<head>
<script type="text/javascript">
try
{
document.write(junkVariable)
}
catch(err)
{
document.write(err.message + "<br/>")
}
</script>
</head>
<body>
</body>
</html>
• The output of the above program is
‘junkVariable’ is undefined
• In the above program, the variable
junkVariableis undefined and the usage of this
in try block gives an error. The control is
transferred to the catch block with this error
and this error message is printed in the catch
block.
throw in JavaScript:
There is another statement called throw available
in JavaScript that can be used along
with try…catch statements to throw exceptions
and thereby helps in generating. General
• syntax of this throw statement is as follows:
throw(exception)
• exception can be any variable of type integer or
boolean or string.
<html>
<head>
<script type="text/javascript">
try
{
varexfor=10
if(exfor!=20)
{
throw "PlaceError"
}
}
catch(err)
{
if(err == "PlaceError")
document.write ("Example to illustrate Throw
Statement: Variable exfor not equal to 20.
<br/>")
}
</script>
</head>
<body>
</body>
</html>
The output of the above program is:
Example to illustrate Throw Statement: Variable exfor not equal to 20.
In the above example program, the try block has
the variable exfor initialized to 10. Using the if
statement, the variable value is checked to see
whether it is equal to 20. Since exfor is not
equal to 20, the exception is thrown using the
throw statement. This is named Place Error and
the control transfers to the catch block. The
error catched is checked and since this is equal
to the PlaceError, the statement placed inside
the error message is displayed and the output
is displayed as above.
Example: <!DOCTYPE html> Cont..
<html>
<body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>
<script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "is Empty";
if(isNaN(x)) throw "not a number";
if(x > 10) throw "too high";
if(x < 5) throw "too low";
}
catch(err) {
message.innerHTML = "Input " + err;
}
}
</script></body></html> 110
Form validation program example
<html>
<head>
<script language="javascript">
function validate()
{
var x=f1.t1.value;
var y=f1.t2.value;
var re=/\d|\W|_/g;
if(x==''||y=='')
window.alert("Enter both user id and password");
else if(x.length<6||y.length<6)
window.alert("both user id and password should greater than or equal to 6");
else if((re.test(x)))
window.alert("user name show3uld be alphabets");
else
window.alert("welcome"+" Mr."+x);
}
</script>
</head>
<body bgcolor="green">
<form name="f1">
<center>
User Name<input type="text" name="t1"><br><br>
Password <input type="password" name="t2"><br><br>
<input type="submit" value="submit" onClick=validate()>
<input type="reset" value="reset">
</center>
</form>
</body>
</html>