[Go to site: main page, start]

0% found this document useful (0 votes)
9 views101 pages

JavaScript Basics and Programming Concepts

The document provides an introduction to JavaScript, covering its basic elements, syntax, and programming concepts such as variables, control structures, and functions. It explains the use of JavaScript in web development, including dynamic HTML and object manipulation. Additionally, it outlines the objectives for learning JavaScript and the expected outcomes for users after completing the module.
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)
9 views101 pages

JavaScript Basics and Programming Concepts

The document provides an introduction to JavaScript, covering its basic elements, syntax, and programming concepts such as variables, control structures, and functions. It explains the use of JavaScript in web development, including dynamic HTML and object manipulation. Additionally, it outlines the objectives for learning JavaScript and the expected outcomes for users after completing the module.
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

Contents

JS_1_IntroductiontoJavaScript··················································································································2
JS_2_JavaScriptObjects························································································································· 35
JS_3_JavaScriptValidations···················································································································· 77
JS_4_JavaScriptRegularExpression······································································································· 89
Web Programming
Javascript

1 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Agenda

1 JavaScript basic elements

2 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Objectives

At the end of this module you will be able to:


• Write JavaScript code using all the basic elements
of JavaScript Programs

3 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


JavaScript basic elements

4 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


DHTML
DHTML stands for Dynamic Hyper Text Markup Language which helps
to add Dynamic content to static HTML pages.

• Dynamic HTML, is a new web technology that enables elements


inside your web page to be, well, dynamic.

• Things once considered unchangeable once the page has loaded,


such as text, page styles (font color, size etc), element position, etc.,
can now all be changed dynamically.

• It brings your web pages one step closer to how things look inside
your television, where images appear and disappear, text flies in and
out, and content moves around freely inside the screen.

• DHTML is any combination of Style Sheets, JavaScript, and Layering.

5 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Introduction to JavaScript

JavaScript is an easy to use object scripting language. It is designed for


creating live online applications. Code is included as part of a HTML
Document

Scripts are run by the Web browser.

6 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Introduction to JavaScript: JavaScript Versus Java

JavaScript can be combined directly with HTML


The JavaScript language structure is simpler than that of
Java
JavaScript is a purely interpreted language
The JavaScript interpreter is built into a Web browser

7 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Introduction to JavaScript: Using the SCRIPT Tag

• The <SCRIPT> tag is an extension to HTML that can enclose any


number of JavaScript statements as shown here:
• <SCRIPT>
• JavaScript statements...
• </SCRIPT>
• A document can have multiple <SCRIPT> tags, and each can
enclose any number of JavaScript statements.
• Unlike HTML, JavaScript is case sensitive.

8 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Introduction to JavaScript: Using the SCRIPT Tag

<HTML>
<HEAD>
<TITLE>Login Page </TITLE>
</HEAD>
<BODY>
HTML Text goes here.
<SCRIPT LANGUAGE="JavaScript">
[Link](“WelCome To green
Bank")
</SCRIPT>
</BODY>
</HTML>

9 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Elements of JavaScript Program

• Elements of JavaScript Program can be divided into five categories,


as follows:

• Variables

• Expressions

• Control Structures

• Functions

• Objects and Arrays

10 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Elements of JavaScript Program: Variables

• Data Types

• Rules for variable names

• Variable Declaration and Scope

11 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Elements of JavaScript Program: Variables

Data Types and Variables


• You can use data in two ways:
• As a literal or constant value
• As a variable
• The four fundamental data types used:
• Numbers
• Boolean, or logical values
• Strings
• The null value/ the object

12 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Elements of JavaScript Program: Variables

Rules for variable names

• Variable names can include alphabets, digits and the


underscore

• (_)

• The first character can be either an alphabet or the underscore

• Are case-sensitive

• There is no official limit on the length of variable names, but they


must fit within one line.

13 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


JavaScript Statements

Conditional statements: if...else and switch

Loop Statements: for, while, do…while, break and


continue

Object Manipulation Statements and Operators:


new, this and with

Comments: single-line (//) and multi-line (/*...*/)

14 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


JavaScript Statements: if else
• if...else Statement
• Use the if statement to perform certain statements if a logical
condition is true; use the optional else clause to perform other
statements if the condition is false. An if statement looks as follows:

if (condition) {
statements1
}
else {
statements2
}

• The condition can be any JavaScript expression that evaluates to


true or false. The statements to be executed can be any JavaScript
statements, including further nested if statements. If you want to use
more than one statement after an if or else statement, you must
enclose the statements in curly braces: {}.

15 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


What will this code print ?
<html>
<body>
<script language="JavaScript">
var a=4, mesg=" ";
if(a==0){
[Link](a+" can't be odd or even"+"<BR>");
}
else{
if(a%2==0)
mesg="Even";
else
mesg="Odd";
[Link](x+" is "+ mesg);
}
</script>
</body></html>

16 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


JavaScript Statements: Switch Statement

• A switch statement allows a program to evaluate an expression


and attempt to match the expression's value to a case label

• If a match is found, the program executes the associated


statement

• A ‘switch’ statement looks as follows:

switch (expression){
case label :
statement;
break;
default : statement;
}
17 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL
JavaScript Statements: Switch Statement

• The program first looks for a label matching the value of expression
and then executes the associated statement. If no matching label is
found, the program looks for the optional default statement, and if
found, executes the associated statement. If no default statement is
found, the program continues execution at the statement following the
end of switch.
• The optional break statement associated with each case label
ensures that the program breaks out of switch once the matched
statement is executed and continues execution at the statement
following switch. If break is omitted, the program continues execution
at the next statement within the switch statement itself.

18 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


What will this code print ?
<script language="javascript">
var choice = 3, Login=" "
switch(choice){
case 1: login = "Manager"
break;
case 2: login = "Staff"
break;
default: login = "Customer";
}
[Link]("you have Logged in As "+login)
</script>

19 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


JavaScript Statements: for Statement

When a for loop executes, the following occurs:

Step 1: The initializing expression ‘initial-expression’, if any, is

executed. This expression usually initializes one or more loop counters,

but the syntax allows an expression of any degree of complexity.

Step 2: The ‘condition’ expression is evaluated. If the value of condition

is true, the loop statements execute. If the value of condition is false,

the for loop terminates.

Step 3: Assuming that the condition is true, the statements execute.

Step 4: Finally, the update expression ‘increment-expression’ executes

and control returns to step 2.

20 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


JavaScript Statements: for Statement

A for loop repeats until a specified condition evaluates to false. A ‘for’

statement looks as follows:

for ([initial-expression]; [condition]; [increment-expression]) {

statements

21 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


JavaScript Statements: for Statement

Simple example to understand For Loop and if:

<SCRIPT language="javascript">
var loginstatus;
for(loginstatus=1;loginstatus<=3;loginstatus++){
if(loginstatus==1){
[Link](" Status=1 You can be Login As Manager");
}
if(loginstatus==2){
[Link](" Status=2 You can be Login As Staff");
}
if(loginstatus==3){
[Link](" status=3 You can be Login As Customer");
}
}

</SCRIPT >

22 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


What will this code print ?
<html>
<body>
<script language="JavaScript">
var x,y;
for(x=19;x>0;x--){
for(y=1;y<=x;y++)
[Link](x+" ");
[Link]("<BR>");
}
</script>
</body>
</html

23 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


JavaScript Statements: do…while Statement

• The do...while statement repeats until a specified condition evaluates to


False

• A ‘do...while’ statement looks as follows

do {
statement
} while (condition)
Statement executes once before the condition is checked. If condition
returns true, the statement executes again. At the end of every
execution, the condition is checked. When the condition returns
false, execution stops and control passes to the statement
following do...while.

24 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


What will this code print ?
<SCRIPT language="javascript">

var num = 1234566


var count = 0
do {
count++;
num /= 10;
} while (num>1);

[Link](“total digits”+count);
</ SCRIPT >

25 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


JavaScript Statements: while Statement
• A while statement executes its statements as long as a specified condition
evaluates to true

• If the condition becomes false, the statements within the loop stop executing
and control passes to the statement following the loop. The condition test
occurs before the statements in the loop are executed. If the condition
returns true, the statements are executed and the condition is tested again. If
the condition returns false, execution stops and control is passed to the
statement following while.

• A ‘while’ statement looks as follows

while (condition) {
statements
}

26 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


What will this code print ?
<html><body>
<script language="JavaScript">
var x=123;
var y=0;
var z;
while(x>0){
z=x%10;
y+=z;
x=parseInt(x/10);
[Link](x+"<BR>");
[Link](y+"<BR>");
[Link](z+"<BR>");
}
[Link](y);
</script>
</body></html>
27 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL
Functions
Functions are one of the fundamental building blocks in
JavaScript. A function is a JavaScript procedure: a set of
statements that performs a specific task. To use a
function, you must first define it, then your script
can call it.

A function definition looks as follows:

function gcd(m,n) {
return n > 0 ? gcd(n,m%n) : m ;
}

28 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Functions

A function definition consists of the function keyword, followed by the

name of the function, a list of arguments to the function, enclosed in

parentheses and separated by commas. The JavaScript statements

that define the function are enclosed in curly braces: { }. The

statements in a function can include calls to other functions defined in

the current application. It is good practice to define all your functions in

the HEAD of a page so that when a user loads the page, the functions

are loaded first.

29 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Functions
<script language="javascript">
function interest(amt,per)
{
var m=(per/100)*amt;
return m;
}

var amount=50000;
var per=6;
totalbalance= amount+interest(amount,per) ;
[Link](totalbalance);
</script>

30 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


What will this code print ?
<html>
<body>
<script language="JavaScript">
function gcd(m,n){
return n > 0 ? gcd(n,m%n):m;
}
[Link](gcd(96,16));
</script>
</body>
</html>

31 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Summary

In this module, you were able to:


• Write JavaScript code using all the basic elements of
JavaScript Programs

32 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


JavaScript
JavaScript Objects

1 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Agenda

1 JavaScript Objects

2 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Objectives

At the end of this module you will be able to:


• Create Windows & Dialog Boxes
• Use the JavaScript’s in-built objects in a web page
• Write code that does Event Handling in HTML pages
• Manipulate HTML Forms through JavaScript
dynamically

3 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


JavaScript Objects

4 © 2012 WIPRO LTD | [Link]


Objects

An object is a self-contained unit of code having


the following characteristics:
• Properties
• Methods
• Identity

5 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Objects

• Like variables, objects can store data - but they can store more
pieces of data at once.

• The items of data stored in an object are called the Properties


of the object.
• E.g: A person object might include [Link] and
[Link], where Bob is the object and address & phone are
its properties.

• Objects have methods or functions which work with the


object’s data.
• E.g: A person object might include a display() method to
display the person’s information.

6 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Objects: The Window Object

At the top of the browser hierarchy is the window object,


which represents a browser window

The properties/methods of this object are:


status
alert()
confirm()
prompt()

7 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Objects: The Window Object
The [Link] is a property which can be used to change the contents
of the browser’s status line. The [Link]() method can be used to
alert the user in case of closing the window before saving the document. It
appears as a dialog box with a exclamatory sign.
The [Link]() method can be used to prompt the user to ask for
clarification. It opens a dialog box with a question mark and two buttons
with ok and cancel as options. The [Link]() method can be used
to prompt the user in case of accessing any data from the user, such as
user name and password. It opens a dialog box with a text box to accept
data from the user.
Simple Example:
<SCRIPT LANGUAGE="JavaScript">
function hello(){
[Link]("You are about to view the Transaction Details ");
}
</SCRIPT>
<P> Click <A HREF = "transaction-
[Link]">MiniStatement </A>
</P>

8 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Objects: The Document Object

The Document Object represents characteristics of the


current HTML page. Some of its properties are:
• title - lastModified
• fgColor - bgColor

One of its most important method is :


• write()

In the browser object hierarchy, the document object is


contained in a window object (for a page without frames)

9 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Objects: The Document Object
The properties of the document object represent characteristics of the
current HTML page. Many of these are specified in the <BODY> tag of
the document while some are set by the browser when the document is
loaded.
The title property lists the title of the current page, defined by the HTML
<TITLE> tag.
The last modified property is the date the document was last modified.
Example:
<HEAD>
<TITLE> Test JavaScript </TITLE>
<SCRIPT Language="JavaScript">
[Link]([Link]+" <BR>");
[Link]([Link]());
</SCRIPT>
</HEAD>

10 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Objects: The Form Object

The Form object represents an HTML Form. It has the same name as
the NAME attribute in the FORM tag

In the browser object hierarchy, the form object is contained in the


document object

• For example, if the first form in a document has the name form1, you
can refer to it in one of two ways:
• document.form1
• [Link][0]

11 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Objects: Frame Objects

Each Frame in a frame set is represented as a frame object.

A frame set contains an array of frame objects representing all the


frames in it.

You can refer to a particular frame:


• By name - if it has one
• By reference to the parent and the array index of that frame

12 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Objects: Frame Objects

• JavaScript allows you to manipulate frames and contents of


frames by providing objects that represent the frames in the
current frameset.

• The frames are either available as objects with the same name
as the frame name or as an array of frames.

• To access one frame from another frame in the same frameset,


you need to use the ‘parent’ frame as a reference through
which the other frames can be accessed. If there are multiple
levels of nested frames, the ‘top’ frame can be used as the
reference to access other frames.

13 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Objects: The Math Object
The Math object can’t be created, since it exists automatically in all
Java Script Programs.

Its properties represent mathematical constants.


Eg:[Link]

Its methods are mathematical functions.


• Three of the most useful methods of the Math object enable you to
round decimal values up and down:
• [Link]() rounds a number up to the next integer.
• [Link]() rounds a number down to the next integer.
• [Link]() rounds a number to the nearest integer.

• All these take a single parameter: the number to be rounded. You


might notice one thing missing: the ability to round to a decimal place,
such as for dollar amounts. You can easily simulate this, though.

14 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Math methods
abs(x) Returns absolute value of x
ceil(x) Returns the smallest integer greater than or equal to x
(round up)
cos(x) Returns cosine of x, where x is in radians

floor(x) Returns the largest integer less than or equal to x (round


down)
log(x) Returns the natural logarithm (base E) of x

max(a, b) Returns the larger of a and b


min(a, b) Returns the lesser of a and b

random()
Returns a pseudorandom number between 0 and 1
round(x) - Rounds x up or down to the nearest integer. It rounds .5
up
15 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL
What will this code print ?
<html>
<script language = "JavaScript">
var x=20;
var y=7;
var a1= [Link](x/y);
var a2 = [Link](x/y);
var a3 = [Link](x/y);
[Link]("ceil = "+a1+"<BR>");
[Link]("floor = "+a2+"<BR>");
[Link]("round = "+a3+"<BR>");
</script>
</body>
</html>

16 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Objects: The String Object

Any String variable in JavaScript is a String object. String


object have a single property, length.

Concatenating strings (+)


indexOf
lastIndexOf
charAt
length
split
substring
substr
toLowerCase and toUpperCase
17 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL
Objects: The String Object

You can perform string functions using a variety of methods.


Methods enable you to convert strings, work with pieces of strings, search
for values, control the string's appearance on the HTML page, and control
HTML links and anchors.
String Conversions methods:
toUpperCase() converts all characters in the string to uppercase.
toLowerCase() converts all characters in the string to lowercase.
Examples:
<script language=“javascript”>

[Link](“Wipro” + “EC4”); //Concatenation


var b = 'I am a JavaScript hacker.'
[Link]([Link]('a'))
[Link]([Link](‘w'))
[Link]([Link](4,8)); // extract characters from 4 to 8 location
[Link]([Link](4,8)); // extract 8 characters from 4 location
</script>

18 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


What will this code print ?
<html><body>
<script language="JavaScript">
var url="[Link]
var x = [Link]("wipro");
[Link]("The string wipro is located at
"+x+" position<BR>");
var y = [Link]("o");
var z = [Link]("o");
[Link]("The first occurence of the
character 'o' is at “+y+" position<BR>");
[Link]("The last occurence of the
character 'o' is at “+z+" position<BR>");
var a = [Link](23);
[Link]("The character at the position
23 is “ +a);
</script>
</body></html>
19 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL
What will this code print ? (Contd.).

<script language="javascript">
var x= "zero one two three four";
var SplitResult = [Link](" ");

for(i = 0; i < [Link]; i++){


[Link]("<br /> Element " + i + " = " +
SplitResult[i]);
}
</script> Output :
Element 0 = zero
Element 1 = one
Element 2 = two
Element 3 = three
Element 4 = four

20 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


What will this code print ? (Contd.).
<html>
<body>
<script language="JavaScript">
var x;
alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
x=[Link](7,12);
y=[Link](7,12);
[Link](x+"<BR>");
[Link](y);
</script>
</body>
</html>

21 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


String Object & Comparison Operators

The following are the different Comparison Operators available in


Javascript.
>, <, >=, <=, !=, == and ===

While we are aware of the uses of most of these operators, we may not
have used “===“ till now.
“==“ and “===“ are both used to compare the values, but there is a
difference.

“==” represents “is equal to”


“===” represents “is exactly equal to” (It will not only check whether the
values are equal or not but also whether the data type is same or not)

Let us understand the difference through an example given in the next


slide.

22 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


String Object & Comparison Operators (Contd.).

function comparing(){ Here in2 stores


var in1=[Link]; an integer value
var in2=10;
if(in1==in2) {
[Link]("Both the values are equal <BR>");
if(in1===in2)
[Link]("Both the values are of same type");
else
[Link]("Both the values are of different
type");
}
else
[Link]("Both the values are unequal");
}

23 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


String Object & Comparison Operators (Contd.).
<form name="f1"> Enter only digits :
<input type="text" name="t1" />
<input type = button value = "Click here"
/>
</form>

Output :
Both the values are equal
Both the values are of different type

24 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


String Object & Comparison Operators (Contd.).
function comparing(){ Here in2 stores
var in1=[Link]; a String value
var in2=“10”;
if(in1==in2) {
[Link]("Both the values are equal <BR>");
if(in1===in2)
[Link]("Both the values are of same type");
else
[Link]("Both the values are of different
type");
}
else
[Link]("Both the values are unequal");
}

25 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


String Object & Comparison Operators (Contd.).
<form name="f1"> Enter only digits :
<input type="text" name="t1" />
<input type = button value = "Click here"
/>
</form>

Output :
Both the values are equal
Both the values are of same type

26 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Objects: The Date Object
The Date object is a built-in JavaScript object that enables you to
conveniently work with dates and times.

You can create a Date object any time you need to store a date, and
use the Date object's methods to work with the date.

You can create a Date object using the new keyword.

You can use any of the following formats:

birthday = new Date();


birthday = new Date("June 20, 1996 08:00:00");
birthday = new Date(6, 20, 96);
birthday = new Date(6, 20, 96, 8, 0, 0);

27 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Some Important Keywords

• The “this” Keyword


“this” is used to refer to the current object

• The “with” Keyword


You can use it to make JavaScript programming easier-or at least
easier to type

The with keyword specifies an object and it is followed by a set of


statements enclosed in braces

28 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Some Important Keywords
<html>
<script language = "JavaScript">
function tot() {
with([Link]) {
var x=parseInt([Link])
var y=parseInt(elements[1].value)
var z=parseInt([Link])
[Link] = x+y+z
}
}
</script>
<form name = "Simple">
<input type = "text" size = "4" name = first value = " "> <BR>
<input type = text size = 4 name = second value = " "> <BR>
<input type = text size = 4 name = third value = " "> <BR>
<input type = button value = "Click" <BR>
<input type = text name = sum value = " "> <BR>
</form>
</html>

29 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Arrays

Arrays need to be created using new keyword

Once you define the array, you can access its elements by
using brackets to indicate the index

For example, the statement to create an array called scores


with 20 values is as follows: scores= new Array(20)

• Array Object Methods :


- join()
- reverse()
- sort()

30 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Arrays
Once you define the array, you can access its elements by using brackets
to indicate the index . As an example, this statement creates an array
called scores with 20 values:
Scores = new Array(20);
Array object methods:
join() quickly joins all the array's elements, resulting in a string. The
elements are separated by commas by default.
reverse() returns a reversed version of the array: the last element becomes
the first, and the first element becomes the last.
sort() returns a sorted version of the array.

<script language="javascript">
var Name=new Array(2);
Name[0]="Raghu";
Name[1]="Kiran"
var s=new Array("Saab","Volvo","BMW");
for( var i=0;i<[Link];i++)
[Link](s[i]);
for( var k=0;k<[Link];k++)
[Link](Name[k]);
</script>

31 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Events
Events refer to things that happen to the browser and is
used to trigger portions of program.
Events pertain to the web page containing the script.
• When the user clicks on a link, selects or enters text, or
even moves the mouse over part of the page, an event
occurs.
• You can use JavaScript to respond to these events. For
example, you can have custom messages displayed in
the status line (or somewhere else on the page) as the
user moves the mouse over links. You can also update
fields in a form whenever another field changes.

32 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Events

• onBlur Occurs when an object on the page loses focus


• onChange Occurs when a text field is changed by the user
• onClick Occurs when the user clicks on an item
• onFocus Occurs when an item gains focus
• onLoad Occurs when the page (or an image) finishes loading
• onMouseOverOccurs when the mouse pointer moves over an item
• onMouseOut Occurs when the mouse pointer moves off an item
• onSelect Occurs when the user selects text in a text area
• onSubmit Occurs when a submit button is pressed
• onUnload Occurs when the user leaves the document or exits

33 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Events: Event Handlers

Embedded in html tags, typically as part of forms, but are


also included as a part of some anchors and links

Virtually anything a user can do to interact with a page is


covered with the event handlers, from moving the mouse
to leaving the current page

34 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Time Outs

Time outs refer to Statements that will be executed after a


certain amount of time elapses.

Handy for periodically updating a Web Page or for delaying


the display of a message or execution of a function.

35 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Time Outs
You begin a timeout with the setTimeout() Method.
Before a timeout has elapsed, you can stop it with the clearTimeout()
method, specifying the identifier of the timeout to stop.
// Update a page every 2 seconds
var counter = 0;
// call Update function in 2 seconds after first load
ID=[Link]("Update();",2000);
function Update(){
counter++;
[Link]="The counter is now at "+counter;
[Link]="The counter is now at "+counter;
//set another timeout for the next count
ID=[Link]("Update();",2000);}
<FORM NAME="form1">
<INPUT TYPE="text" NAME="input1" SIZE="40"><BR><INPUT
TYPE="button" VALUE="RESET" > <INPUT TYPE="button" VALUE="STOP"
> </FORM>

36 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Creating Windows
Opening new browser windows is a great feature of JavaScript.

You can either load a new document (for example a HTML-


document) to the new window or you can create new documents
(on-the-fly).
• Here is a list of the properties a window can have:

• directories yes|no
• height number of pixels
• location yes|no
• menubar yes|no
• resizableyes|no
• scrollbars yes|no
• status yes|no
• toolbar yes|no
• width number of pixels

37 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Example to create New Window
Example to create New Window [Link]("</font></center>");
[Link]("</body></html>");
<html>
<head> // close the document - (not the window!)
<script language="JavaScript"> [Link]();
<!-- hide }
function openWin3() { // -->
myWin= open("", "displayWindow", </script>
</head>
"width=500,height=400,status=yes,toolbar=yes,menuba <body>
r=yes"); <form>
// open document for further output <input type=button value="On-the-fly" > [Link](); </form>
// create document </body>
[Link]("<html><head><title>On-the- </html>
fly");
[Link]("</title></head><body>");
[Link]("<center><font size=+3>");
[Link]("This HTML-document has
been created ");
[Link]("with the help of JavaScript!");

38 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Quiz
What happens when you move the mouse pointer on the image displayed?

<html>
<body bgcolor="pink">
<img name=ash src="[Link]" > > <script>
function vh() {
[Link]="[Link]";
}
function hv(){
[Link]="[Link]";
}
</script>
</body></html>

39 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Quiz (Contd.).
What happens when you move the mouse pointer on the image displayed? What
happens when you move the mouse pointer out of the image?

<html>
<img name=ash src="[Link]" > > <script>
function vh(){
[Link]=[Link]+1;
[Link]=[Link]+1;
}
function hv(){
[Link]=[Link]-100;
[Link]=[Link]-100;
}
</script></body></html>
40 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL
Summary

In this module, you were able to:


• Create Windows & Dialog Boxes
• Use the JavaScript’s in-built objects in a web page
• Write code that does Event Handling in HTML pages
• Manipulate HTML Forms through JavaScript dynamically

41 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Web Programming
Javascript

1 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Agenda

1 JavaScript Validations

2 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Objectives

At the end of this module you will be able to:


• Validate user inputs through javascript functions

3 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


JavaScript Validations

4 © 2012 WIPRO LTD | [Link]


Javascript Validation Example 1
• The following example demonstrates how you can define a
function that is going to ensure that the text box cannot remain
empty :

<html>
<head>
<title>Handling Form Data</title>
<script>
function chkfrm(){
var x=[Link];
if([Link]==0){
alert("Please Enter Name \n");
return false;
}
Contd..

5 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Javascript Validation Example 1 (Contd.).
else{
return true;
}
}
</script></head>
<body>
<form name ="card" method=post action="Hello"
chkfrm();">
<center>
<B> Enter Your Name : </B>
<p><input type="text" name="name" >
<p><input type="submit" value="submit">
</center>
</form></body>
</html>

6 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Javascript Validation Example 2
• The following example demonstrates how you can define a
function that is going to ensure that exactly 10 digits are
entered in the text box :
<html>
<head><script>
function chkfrm(){
var flag=0;
var x=[Link];
if([Link]!=10){
if(!isNaN(x))
alert("You are expected to enter 10
digits");
}
else
flag = flag + 1; Contd..
7 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL
Javascript Validation Example 2 (Contd.).
if(isNaN(x))
alert("Only digits nothing else");
else
flag = flag+1;
if(flag==2)
return true;
else
return false; }
</script></head><body>
<form name ="card" method=post > chkfrm();">
<center><B> Enter Your Mobile No(exactly 10 digits) :
</B>
<p><input type="text" name=“mob" >
<p><input type="submit" value="submit"></center>
</form></body>
</html>
8 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL
Javascript Validation Example 3
• The following example demonstrates how you can define a function
that is going to ensure that only alphabets(lower as well as upper
case) and space(keycode=32) can be entered in the text box :

<script language="Javascript">
function ValidateAlpha(){
var keyCode = [Link];
if ((keyCode < 65 || keyCode > 90) && (keyCode < 97
|| keyCode > 123) && keyCode != 32){

[Link] = false;
alert("Only alphabets or space..please");
}
}
</script>
Contd..
9 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL
Javascript Validation Example 3(Contd.).

<form method=“post” action=“xyz” >


Enter your Name :
<input type="text" id="txtBox"
/>
</form>

10 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Summary

In this module, you were able to:


• Validate user inputs through javascript functions

11 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Web Programming
Javascript

1 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Agenda

1 JavaScript Regular Expressions

2 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Objectives

At the end of this module you will be able to:


• Understand the use of regular expressions
• Validate user inputs using regular expressions

3 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


JavaScript Regular Expressions

4 © 2012 WIPRO LTD | [Link]


Regular Expression in Javascript
• The most difficult part of creating user interface for a web
application is user validation

• Developing user interfaces that will be accessed by different


browsers is much more painful, due to lack of useful validation
functions in Javascript

• Luckily, Javascript (version 1.2 and above) has incorporated


regular expressions, using which we can perform validations
easily

• Regular expression are tools for performing pattern matching

• We can perform complex task that requires lengthy procedures


with just few lines using regular expressions

5 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Use of Patterns
• Regular expressions are implemented in Javascript in the
following way:

• var regexp = /pattern/

• To use regular expressions to validate a String you need


to define a pattern String that defines the search criteria

• Use a relevant String method to denote actions like


search or test

• Patterns are defined using String literal characters or


meta characters

6 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Metacharacters

• Metacharacters are characters with special meaning

Metacharacter What it means


\d Find a digit
\D Find a non-digit character
\w Find a word character
\W Find a non-word character
\s Find a whitespace character
\S Find a non-whitespace character
\b Find a match at the beginning or end of a word
\B Find a match not at the beginning or end of a word

7 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Example 1
• The following example demonstrates how to use patterns that
will check whether the key pressed is a digit or not :

<html>
<body>
<script language="javascript">
function onlyNumbers(e){
var keynum
var keychar
var numcheck
if([Link]) {
keynum = [Link]
}
Contd..

8 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Example 1 (Contd.).

keychar = [Link](keynum)
numcheck = /\d/
return [Link](keychar)
}
</script>

<form>
<input type="text" > onlyNumbers(event)" />
</form>
</body>
</html>

9 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Example 1 (Contd.).

• When the user presses any key, an event is generated. The key on
which the event is generated, is stored in the variable keynum by
capturing the keycode.
• The javascript String method fromCharCode() is used to convert the
unicode value to character and it is stored in the variable keychar.
• The variable numcheck defines a pattern for searching. Here \d is the
metacharacter, which is used to find a digit.
• The String method test() is used to match the pattern(here it is trying
to match the character obtained from the keypress with \d, i.e a digit).
• Thus, the function onlyNumbers() will return the value of the keypress
only if it is a digit(0 – 9). It will not return any other character.

10 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Brackets

• Brackets are used to find a range of characters

Expression What it means


[xyz] Find any character between the brackets
[^xyz] Find any character not between the brackets
[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
[0-9] Find any digit from 0 to 9
[Bandra|Andheri|Borivli] Find any of the alternatives specified

11 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Example 2
• The following example demonstrates how to use patterns that will
check whether the key pressed is an alphabet(Lower case or
upper case):

<html>
<body>
<script language="javascript">
function onlyCharacters(e){
var keynum
var keychar
var charcheck
if([Link]) {
keynum = [Link]
}
Contd..
12 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL
Example 2 (Contd.).

keychar = [Link](keynum)
charcheck = /[A-Za-z]/
return [Link](keychar)
}
</script>

<form>
<input type="text" > onlyCharacters(event)" />
</form>
</body>
</html>

13 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Quiz
What happens when you move the mouse pointer on the image displayed?

<html>
<body bgcolor="pink">
<img name=ash src="[Link]" > > <script>
function vh() {
[Link]="[Link]";
}
function hv(){
[Link]="[Link]";
}
</script>
</body></html>

14 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL


Quiz (Contd.).
What happens when you move the mouse pointer on the image displayed? What
happens when you move the mouse pointer out of the image?

<html>
<img name=ash src="[Link]" > > <script>
function vh(){
[Link]=[Link]+1;
[Link]=[Link]+1;
}
function hv(){
[Link]=[Link]-100;
[Link]=[Link]-100;
}
</script></body></html>
15 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL
Summary

In this module, you were able to:


• Understand the use of regular expressions
• Validate user inputs using regular expressions

16 © 2012 WIPRO LTD | [Link] | CONFIDENTIAL

You might also like