Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
51 views

Chapter 4 Javascript

The document summarizes client-side scripting using JavaScript. It covers introducing JavaScript and how it enables dynamic web pages. It also discusses running JavaScript code, adding JavaScript through external files or inline, and using different types of input-output methods. The document then covers working with variables and data types in JavaScript as well as operators and expressions.

Uploaded by

Hayome Takele
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Chapter 4 Javascript

The document summarizes client-side scripting using JavaScript. It covers introducing JavaScript and how it enables dynamic web pages. It also discusses running JavaScript code, adding JavaScript through external files or inline, and using different types of input-output methods. The document then covers working with variables and data types in JavaScript as well as operators and expressions.

Uploaded by

Hayome Takele
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 80

Chapter 4

Client Side Scripting in JavaScript


1. Introduction
 In the very beginning, web pages were static without any
interaction with the user.
 They just provide information to the user as it is.
 JavaScript is introduced to enable dynamicity in web pages
where user has his/her own preferences or control.
 JavaScript is a cross-platform, object-oriented scripting
language modeled after C++.
 Scripting languages are programming languages that are
generally easy to learn, easy to use, excellent for small
routines and applications, and developed to serve a particular
purpose.
1. Introduction…
 JavaScript was written for the express purpose of adding
interactivity to Web pages.
 As a scripting language, JavaScript is easy to learn and easy to use.
 You can embed commands directly into your HTML code and the
browser will interpret and run them at the appropriate time.
 JavaScript is also much more forgiving than compiled languages
such as Java and C++.
 Its syntax is simple and easy to read.
 Scripting languages are usually interpreted rather than compiled.
 Programs written in interpreted languages must be translated into
machine code every time they are run
2. Running the JavaScript…
<script language=”JavaScript”>
//your script here
</script>

 Here are some tips to remember when writing JavaScript


commands:
 JavaScript code is case sensitive (e.g. age and Age are

different variables)
 White space between words and tabs are ignored

 Line breaks are ignored except within a statement

 JavaScript statements end with a semi colon (;)


Adding JavaScript
 There are three ways to add JavaScript commands to your
Web Pages.
 Embedding code

 Inline code

 External file

I. External File
 If you want to run the same JavaScript on several pages, you

can write a JavaScript in an external file.


 Save the external JavaScript file with a .js file extension.
Adding JavaScript…
 The external script cannot contain the <script></script> tags!
 You can use the SRC attribute of the <SCRIPT> tag to call

JavaScript code from an external text file.


 It is called by the following tag:

<SCRIPT language = "JavaScript" SRC = "filename">


</SCRIPT>
II. Scripts in <head>
 Scripts to be executed when they are called, or when an event

is triggered, are placed in functions.


 Put your functions in the head section, this way they are all in

one place, and they do not interfere with page content.


Adding JavaScript…
<html>
<head>
<script language="javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>
<body onload="message()">
</body>
</html>
Adding JavaScript…
III. Scripts in <body>
 If you don't want your script to be placed inside a function, or if
your script should write page content, it should be placed in the
body section.
<html>
<head> </head>
<body>
<script language="javascript">
document.write("This message is written by JavaScript");
</script>
</body>
Input-Output in Java
 In JavaScript, input-output can be done in different
ways:
document.write(“message to display”);
alert(“message to display”);
prompt(“message to display”, “default value”);
confirm(“message to display”);

 documents.write method writes a string to the web page.


 Anything between double quotes will be displayed as it is in
the web page.
 Anything outside of quotes is evaluated as expression and the
result will be sent to the web page.
Input-Output in Java…
 The alert method produces a browser alert box.
 These are useful for debugging and learning the language.
 However, they are not good way to communicate with the users.
 alert() displays a modal window that presents a message to the user
with a single Ok button to dismiss the dialog box.
 The prompt display includes a message, field for user input, and
two buttons (Ok, and Cancel).
 The prompt(“”) returns string of text entered by user.
 It takes two parameters:
 a message providing the prompt for the response, and
 a default string which is used to fill in the text field.
Input-Output in Java…
 A confirm dialog box presents a message in a modal dialog box
along with Ok and Cancel buttons.
 Such dialog boxes can be used to ask the user a question, usually
prior to performing undoable actions.
 The dialog box returns a Boolean value of Ok=true, and
Cancel=false;
 Example:

var adult = confirm(“Are you sure you are older than 18 years?”)
if(adult)
alert(“Yes”);
else
3.Working with Variables and Data

 In JavaScript, a value of a variable can be one of several


types.
 Table lists JavaScript’s formal data types, with examples of
the values.
Type Example Description
String “John” a series of characters inside quotation marks

Number 4.5 any number not inside quotes

Boolean True a logical true or false

Null Null completely devoid of any value

Object Class that is defined by its properties and methods


Declaring Variables
 To declare variable, we use the var keyword, followed by the name of the
variable.
 Therefore, to declare a new variable called myAge:
var myAge;
 Example: correct variable declaration,
var firstName;
var weight;
var he89;
var TH_;
 After declaring a variable, it is possible to assign a value to it by using
equal sign (=) as follows:
var myAge;
myAge = 45;
Redeclaring JavaScript Variables

 If you redeclare a JavaScript variable, it will not lose its


original value.
var age=5;
var age;
 After the execution of the statements above, the variable x
will still have the value of 5.
 The value of x is not reset (or cleared) when you redeclare it.
 JavaScript is loosely typed.
 Variables can store any type of data.
var value=“Hello world!”;
value = 30.5;
Comments
 JavaScript supports two types of comments:
 Comments on a single line are preceded by //.

 Comments that span multiple lines are preceded by /* and

followed by */

 Example: the following example shows two comments:


//This next line prints text into the document
document.write("This line came from some JavaScript");
/* This is a multiple-line comment. This line shows an
alert so we know things worked properly */
alert("The text has been printed");
4. Operators and Expressions
 An operator performs some kind of operation or comparison
with two values to reach a third value.
 Generally, operators can be broadly categorized into four:
 Arithmetic operators,
 Assignment operators
 comparison operators and
 logical operators.

I. Arithmetic Operators
 Arithmetic operators are used to perform arithmetic

operations between variables or values.


4. Operators and Expressions…

Operator Description
+ Perform addition of numbers
- Perform Subtraction
* Multiply numbers
/ Divide numbers
% Modulus (performs division and gets the remainder)
++ Increment
-- Decrement
4. Operators and Expressions…
 Example:
<script language=“JavaScript”>
var x;
var y=5;
x = y+2; //x=7
x = y-2; //x=3
x = y*2; //x=10
x = y/2; //x=2.5
x = y%2; //x=1
x = ++y; //x=6
x = --y; //x=4
</script>
4. Operators and Expressions…
II. JavaScript Assignment Operators
 Assignment operators are used to perform arithmetic

operation and then assign the result to variables.


Operator Description

= assignment operator
+= Add and then assign

-= Subtract and then assign

*= Multiply and then assign

/= Divide and then assign

%= Modulate and then assign


4. Operators and Expressions…
<script language=“JavaScript”>
var x=10;
var y=5;
x=y; //x=5;
x+=y; //x=10
x-=y; //x=5
x*=y; //x=25
x/=y; //x=5
</script>
4. Operators and Expressions…
III. Comparison Operators
 Comparison operators help you compare two or more values

 They compare whether the two values are equal or not.

Symbol Description
== Equals
=== Exactly equal to (value and type)
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
4. Operators and Expressions…
IV. Logical Operators
 Logical operators are used to determine the logic between

variables or values.
Operator Description
&& And
|| Or
! Not

Given that x=6 and y=3, the table shows logical operators:
Example Result
(x<10 && y>1) true
(x==5 || y==5) false
!(x==y) true
Operator type Individual operators
member . []
call / create instance () new
negation/increment ! ~ - + ++ -- typeof void delete

multiply/divide * / %
Operator Precedence

addition/subtraction + -
bitwise shift << >> >>>
relational < <= > >= in instanceof
equality == != === !==
bitwise-and &
bitwise-xor ^
bitwise-or |
logical-and &&
logical-or ||
Conditional ?:
assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=
comma ,
Data Type Conversions
 JavaScript provides two built-in functions to convert string representations
of numbers to true numbers:
 parseInt(string [,radix])

 parseFloat(string [,radix])

radix, which is optional, specifies the base of the number to


convert to: hexadecimal, octal, or decimal, ..

 To use either of these conversion functions, pass the string value you wish
to convert as a parameter to the function.
 Look at the results of two different string values when passed through the
parseInt() function:
parseInt(“42”) // result = 42
parseInt(“42.33”) // result = 42
Data Type Conversions…
 The parseFloat() function returns an integer if it can
 Otherwise, it returns a floating-point number as follows:
parseFloat(“42”); // result = 42
parseFloat(“42.33”); // result = 42.33

 JavaScript gravitates toward strings when faced with an


expression containing mixed data types
 The simplest way to convert a number to a string is by adding
an empty string to a number:
(“” + 2500); // result = “2500”
(“” + 2500).length; // result = 4
Data Type Conversions…
 A more elegant way is to use the toString([radix]) method.
 For example, to convert the dollars variable value to a string, use
this statement:
Var dollars = 2500;
dollars.toString(); // result = “2500”
 You can specify a number base for the string representation of the
number.
 Called the radix, the base number is added as a parameter to the
method name.
 Here is an example of creating a numeric value for conversion to its
hexadecimal equivalent as a string:
var x = 30;
var y = x.toString(16); // result = “1e”
Data Type Conversions…

var someVal = 2;
someVal = someVal + 2;
someVal = someVal * 10;
someVal = someVal + “20”;
someVal = “Robert”;
5. Working with Conditional Statements

 Conditional statements are used to perform different actions based


on conditions.
 Broadly, there are two ways to execute code conditionally:
 If statement

 switch statement

If condition
 The simplest program decision is to follow a special branch or path
of the program if a certain condition is true.
 Formal syntax for this construction follows:
if (condition) {
statement[s] if true
}
5. Working with Conditional Statements…

Example:
if (myAge < 18) {
alert(“Sorry, you cannot vote.”)
}
if . . . else Condition
 Not all program decisions are as simple as the one shown

above.
 The program may follow one of many branches depending on

the condition.
 But if processing must follow one of two special paths, you

need the if...else construction.


5. Working with Conditional Statements…

if (condition) {
statement(s) if true
}
[else if(condition){
statement(s) if true
}]
[else {
statement(s) if false
}]

 [] indicates optional parts of the JavaScript code.


5. Working with Conditional Statements…

 Example:
If(mark>80)
status=”excellent”;
else if(mark>60)
status=”very good”;
else if(mark>50)
status = “fair”;
else
status =”poor”;
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.
switch (expression) {
case label1:
statements1
[break;]
case label2:
statements2
[break;]
...
default:
statementsdefault
[break;]
5. Working with Conditional Statements…

 Example:
switch (fruittype) {
case "Apples":
document.write("Apples are $0.32 a pound.<br>");
break;
case "Bananas":
document.write("Bananas are $0.48 a pound.<br>");
break;
case "Mangoes":
case "Papayas":
document.write("Mangoes and papayas are $2.79 a pound.<br>");
break;
default:
document.write("Sorry, we are out of " + fruittype + ".<br>");
Working with Loops
 A loop is a set of commands that executes repeatedly until a
specified condition is met.
 JavaScript supports the for, do while, and while loop statements.
 In addition, you can use the break and continue statements within
loop statements.
 Another statement, for...in, executes statements repeatedly but is
used for object manipulation.
 There are three loop statements in JavaScript:
 for Statement

 do...while Statement

 while Statement
Working with Loops…
for Loops
 A for loop repeats until a specified condition evaluates to false.

for ([initialization]; [condition]; [increment]){


Statement(s)
}
 Example: a program that adds numbers from 0 to 10

var counter = 10;


var sum = 0;
for (var i = 0; i <= counter; i++) {
sum = sum + i;
}
document.write(“the sum is ” + sum);
Working with Loops…
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 is true, the statement executes again.
 At the end of every execution, the condition is checked.
 When the condition is false, execution stops.
Working with Loops…
 Example: the do loop iterates until i is no longer less than 5.
var i=1;
do{
document.write(i);
i += 1;
} while (i < 5);

while Statement
 A while statement executes its statements as long as a specified

condition evaluates to true.


 A while statement looks as follows:

while (condition)
{
statement
Working with Loops…
 The condition test occurs before statement in the loop are executed.
 If the condition returns true, statement is executed and the condition is
tested again.
 If the condition returns false, execution stops and control is passed to the
statement following while.

 Example 1: the following while loop iterates as long as n is less than


three:
n = 0;
x = 0;
while (n < 10)
{
n++;
x += n;
}
Working with Loops…
break and continue statements
 Use the break statement to terminate a loop, switch, or label

statement.
 It is used to stop the loop when the condition we need is fulfilled.

 Example: this loops until the value of loop counter is 5:


for (i = 0; i < 100; i++) {
if (i== 5)
break;
}
 The continue statement can be used to restart a while, do-while, for,
or label statement.
 When you use continue, it terminates the current iteration and
continues execution of the loop with the next iteration.
Working with Loops…
 In a while loop, it jumps back to the condition check, and in a for
loop, it jumps to the increment-expression.
 In contrast to the continue statement, break terminates the execution
of the loop entirely.
 Example: a program that adds numbers between 0 and 100 with the
exception of 60, 70, and 80
var counter = 100;
var sum = 0;
for (var i = 0; i <= counter; i++) {
if(i==60 || i==70 || i==80)
continue;
sum = sum + i;
}
document.write(“the sum is ” + sum);
Arrays
 An array is an ordered collection of data.
 You can best visualize an array as a table, not much different
from a spreadsheet.
 To initialize an array for your script, use the new keyword to
construct the object for you while assigning the array object to
a variable of your choice:
var myArray = new Array(n)
where n is the number of entries you anticipate for the array.
 This initialization does not make any array entries or create
any placeholders.
 Such preconditioning of arrays is not necessary in JavaScript.
Arrays…
 Example: an array that stores the names of planets
var planet = new Array(9); //an array with 9 entries
planet[0] = “Mercury”
planet[1] = “Venus”
planet[2] = “Earth”
planet[3] = “Mars”
planet[4] = “Jupiter”
planet[5] = “Saturn”
planet[6] = “Uranus”
planet[7] = “Neptune”
planet[8] = “Pluto”
Arrays…
 You can also create array by directly giving the values:
var planet= new Array(“Mercury”,”Venus”,”Earth”, ”Mars”, “Jupiter”,
“Saturn”, ”Uranus”, ”Neptune”,”Pluto”);

 You can also create the planets array like:


var planet= [“Mercury”, ”Venus”, ”Earth”, ”Mars”, “Jupiter”,
“Saturn”, ”Uranus”, ”Neptune”, ”Pluto”];

 In general, you can create array in three different ways :


arrayName = new Array(arrayLength);
arrayName = new Array(element0, element1, ..., elementN);
arrayName = [element0, element1, ..., elementN];
Arrays…
Access an Array
 You can use the document.write() method to display all the
content of the Array.
 This will produce one long text string that is composed of
each element of the array like this:
document.write(planet);

 This produces the following output:

Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,Plu
to
Arrays…
 You can refer to a particular element in an array by using the
index number.
 The index number starts at 0 and end at n-1 for array of n
entries.
 For example, to access the fifth planet in the planets array, we
use:
document.write(planet[4]); //prints Jupiter

 If you wanted to output each element of the array individually,


you can set up a for () statement like this:
for (var i=0; i < planet.length; i++) {
document.write(planet[i] + "<BR>");
Arrays…
Deleting Array Entries
 You can always set the value of an array entry to null or an empty string
to wipe out the data.
 But with the delete operator, you could not completely remove the
element.

 Deleting an array element eliminates the index from the list of accessible
index values
 But it does not reduce the array’s length
planet.length; // result: 9
delete planet[2];
planet.length; //result: 9
Arrays…
Two Dimensional Arrays
 To create a two-dimensional array, just define two arrays and assign one of the

arrays as an element of the other Array.


 To access the elements of the nested array, you use a second set of index

subscripts.
 You can also create multidimensional array like:

letter = [
["alpha", "beta", "gamma", "delta"],
["blue", "red", "gold", "silver"],
["one", "two", "three", "four"],
["www", "xxx", "yyy", "zzz"]
];

 To display each row:


for(var i=0; i < letter.length; i++)
Arrays…
 The ouput from the above loop:
alpha beta gamma delta
blue red gold silver
one two three four
www xxx yyy zzz

 The above multidimensional array can be created as:


a1 = new Array("alpha", "beta", "gamma", "delta");
a2 = new Array("blue", "red", "gold", "silver");
a3 = new Array("one", "two", "three", "four");
a4 = new Array(“www”, “xxx”, “yyy”, “zzz”);
myArray10 = new Array(a1, a2, a3, a4);
Arrays…
 Example:
myArray1 = new Array("alpha", "beta", "gamma");
myArray2 = new Array("eeny", "meeny", "miney", myArray1);

 The array now looks:


myArray2[0] = "eeny";
myArray2[1] = "meeny";
myArray2[2] = "miney";
myArray2[3] = myArray1;

 And the Elements of myArray1 are:


myArray2[3] [0] = "alpha";
myArray2[3] [1] = "beta";
Arrays…
 A JavaScript-enabled browser creates a number of
internal arrays for the objects in your HTML
documents and browser properties.
 For example, if your document contains five links, the
browser maintains a table of those links.
 You access them by number (with 0 being the first
link) in the array syntax as in document.links[0], which
represents the first link in the document.
Arrays…
Array Object Methods
 array.concat(array2)
 The array.concat() method allows you to join two array objects
into a new, third array object.
 The action of concatenating the arrays does not alter the
contents or behavior of the two original arrays.

 For example:
var array1 = new Array(1,2,3)
var array2 = new Array(“a”,”b”,”c”)
var array3 = array1.concat(array2)
Arrays…
 array.sort([compareFunction])
 This method sorts the elements of an array.
 You can define a compareFunction algorithm if you don’t want to
use the default compare function.

 When no parameter passed to array.sort() method, JavaScript


converts items to strings.
 From there, it performs a string sort of the values.
 ASCII values of characters govern the sort.
 This has strong implications for numeric data:
The value 201 sorts before 88 comparing the first characters of
Arrays…
 You can add additional intelligence is available that you can
add to array sorting.
 The key tactic is to define a function that helps the sort()
method compare items in the array.
 A comparison function is passed two values from the array.
 The comparison function lets the sort() method know which
of the two items comes before the other, based on the value
the function returns.
 Assuming that the function compares two values, a and b,
the returned value reveals information to the sort() method
Arrays…
Return Value Meaning
<0 value b should sort later than a
0 The order of a and b should not change
>0 Value a should sort later than b

Example: a function that sorts numbers


myArray = new Array(12, 5, 200, 80)
function compare(a, b) {
return a - b;
}
myArray.sort(); //12 200 5 80
myArray.sort(compare); //5 12 80 200
Method Description
filter() Creates a new array with all of the elements of this array for which the
provided filtering function returns true.
indexOf(value) Returns the first (least) index of an element within the array equal to the
specified value, or -1 if none is found.
join(separator) Joins all elements of an array into a string using separator

lastIndexOf(value) Returns the last (greatest) index of an element within the array equal to
the specified value, or -1 if none is found.
pop() Removes the last element from an array and returns that element.

push(value) Adds one or more elements to the end of an array and returns the new
length of the array.
reverse() Reverses the order of the elements of an array − the first becomes the
last, and the last becomes the first.
shift() Removes the first element from an array and returns that element.

slice(start [,end]) Extracts a section of an array and returns a new array.

splice(start [,deletecount Replaces and/or removes elements from an array.


[,item1 [,item2 [,…itemN]]]]))

toString() Returns a string representing the array and its elements.

unshift(value) Adds one or more elements to the front of an array and returns the new
length of the array.
function arrayFunction() {
var grade = new Array("70", "60", "80", "90", "20");
document.write("<br> Popped: " + grade.pop());

document.write("<br> After poping:");


for(var i=0;i<grade.length; i++)
document.write(" " + grade[i]);

grade.reverse();
document.write("<br>Reversed: ");
for(var i=0;i<grade.length; i++)
document.write(" " + grade[i]);

document.write("<br>Search 80: " + grade.indexOf("80"));


document.write("<br>Converted to string: " + grade.toString());

var slicedValue = grade.slice(2);


document.write("<br>Sliced: " + slicedValue);
document.write("<br>Spliced: " + grade.splice(1));
grade.unshift("500","6000");
document.write("<br>Final: " + grade);
Arrays…
 This produces the following output:
//70, 60, 80, 90, 20
Popped: 20
After poping: 70 60 80 90
Reversed: 90 80 60 70
Search 80: 1
Converted to string: 90,80,60,70
Sliced: 60,70
Spliced: 80,60,70
Final: 500,6000,90
Functions in JavaScript
 Functions are one of the fundamental building blocks in
JavaScript.
 A function is a set of statements that performs a specific task.
 To use a function, you must first define it, then your script can
call it.

Defining Functions
 A function definition consists the function keyword, followed

by:
 The name of the function.

 A list of arguments to the function, separated by commas.

 The statements that define the function, enclosed in curly

braces { }.
Functions in JavaScript…
 The syntax to define function:
function functionName ( [parameter1]...[,parameterN] ) {
statement[s]
}

 Function names have the same restrictions as variable names.


 You should devise a name that succinctly describes what the function
does.
 It is possible to use multiword names with the interCap format that start
with a verb because functions are action items.

 Example: the following code defines a simple function named square:


function square(number) {
return number * number;
}
Functions in JavaScript…
Function Parameters
 You can define functions so they receive parameter values from
the calling statement.
 Parameters/arguments provide a mechanism for “handing off” a
value from one statement to another by way of a function call.
 If no parameters occur in the function definition, both the
function definition and call to the function have only empty sets
of parentheses.

 When a function receives parameters, it assigns the incoming


values to the variable names specified in the function definition’s
parentheses.
Functions in JavaScript…
 Consider the following script segment:
function sayHiToFirst(first, second, third) {
alert(“Say hello, “ + first)
}
sayHiToFirst(“Gracie”, “George”, “Harry”)
sayHiToFirst(“Larry”, “Moe”, “Curly”)

 After the function is defined in the script, the next statement calls that
very function, passing three strings as parameters.
 The function definition automatically assigns the strings to variables
first, second, and third.
 first evaluates to “Gracie,” second evaluates to “George,” and third
evaluates to “Harry.”
 In the alert() statement, only the first value is used and the alert reads
Functions in JavaScript…
 Unlike other variables that you define in your script, function
parameters do not use the var keyword to initialize them.
 They are automatically initialized whenever the function is

called.
The return Statement
 The return statement is used to specify the value that is

returned from the function.


 So, functions that are going to return a value must use the

return statement.
Functions in JavaScript…
 The example below returns the product of two numbers (a and b):
<html>
<head>
<script language=“JavaScript">
function product(op1, op2)
{
return op1*op2;
}
</script>
</head>
<body>
<script language=“JavaScript">
document.write(product(4,3));
</script>
</body>
JavaScript Objects and Events
1. Managing Events
 Events are occurrences generated by the browser, such as
loading a document, or by the user, such as moving the
mouse.
 They are the user and browser activities to which we may
respond dynamically with a scripting language like
JavaScript.
 There are several more events that we can capture with
JavaScript, but the ones below are, by far, the most popular.
Event Event Handler Description
Load onLoad Browser finishes loading a Web document
Unload onUnload Visitor requests a new document in the browser window
Mouseover onMouseOver Visitor moves the mouse over some object in the document window
Mouseout onMouseOut Visitor moves the mouse off of some object in the document window
MouseDown onMouseDown A mouse button was pressed
MouseMove onMouseMove The mouse moved
MouseUp onMouseUp The mouse button was released
Select onSelect Text has been selected.
Click onClick Visitor clicks the mouse button
Focus onFocus Visitor gives focus to or makes active a particular window or form
element by clicking on it or tabbing to it
Blur onBlur A form field lost the focus (user moved to another field)
Change onChange Visitor changes the data selected or contained in a form element
Submit onSubmit Visitor submits a form
Reset onReset Visitor resets a form
Abort onAbort An image failed to load
Change onChange The contents of a field has changed
DblClick onDblClick User double-clicked on this item
Error onError An error occurred while loading an image
Keydown onKeyDown A key was pressed
KeyPress onKeyPress A key was pressed or released
KeyUP onKeyUp A key was released
Example: a program that adds or subtracts two numbers when respective button is clicked
<html>
<head>
<script language="JavaScript">
function adder(num1, num2)
{
var sum = 0;
sum = num1 + num2;
document.write("The sum is " + sum);
}
function subtractor(num1, num2)
{
var difference = 0;
difference = num1 - num2;
document.write("The difference is " + difference);
}
</script>
</head>
<body>
<form name="event_example">
<input type="button" value="add" name="add" onClick="adder(10,30)">
<input type="button" value="subtract" name="subtract" onClick="subtractor(20,50)">
<a href=“” onclick=“adder(30,40)”> Add </a>
</form>
</body>
</html>
JavaScript Objects and Events…
3.2 Working with JavaScript Objects
 JavaScript has many built-in objects that you can use to perform
different activities.
 Every time you load a page into web browser, the JavaScript
interpreter creates certain Objects based on how the HTML is written.
 This minimal Object set is comprised of the navigator, window,
document, location, and history Objects.
 Depending on what's contained in the page, there can obviously be
other Objects that are also generated by the interpreter.
 All of these Objects exist in an Object hierarchy that can be accessed
by calling on the Object with dot notation.
 The following chart shows the structure.
Form Processing and Validation
 It is possible to access form and form elements from
JavaScript.
 You can set attributes for NAME, TARGET, ACTION,

METHOD, and ENCTYPE for form.


 Each of these is a property of a FORM object, accessed by all

lowercase versions of those words, as in:


document.forms[0].action //forms array of the document
document.formName.action //references exact form by name

 To change any of these properties, simply assign new values


to them:
document.registration.action = “http://www.abc.com/cgi/login.pl”
Form Processing and
Validation…
 Forms support different events:
 onFocus – an event is triggered with a form object gets input focus.
 onBlur – this event is triggered when a form object loses input focus.
 onChange – an event is triggered when a new item is selected in a
list box.
 This event is also trigged with a text or text area box loses focus and
the contents of the box has changed.
 onSelect – an event is triggered when text in a text or text area box is
selected.
 onSubmit – an event is triggered when the form is submitted to the
server.
Form Processing and
Validation…
Text boxes and Text areas
 Text fields have a value property.

 The value property of the input text box, is both readable and writable.

 To access text input fields, you can use the syntax:

value = document.formName.textName.value; //read content


document.formName.textName.value = value; //set content

 Text box and textarea properties:


 name - String value of the NAME attribute.
 value - String value of the contents of the field.
 defaultValue - String value of the initial contents of the field.
 type - Specifies what type of object this form field is (e.g. “text” or
“Textarea”).
Form Processing and
Validation…
Methods
 focus( ) - Sets input focus to the object.

 blur( ) - Removes input focus from the object.

 select( ) - Selects the object's input field.

Event Handlers
 onFocus - executed when input focus enters field (by tabbing in or by

clicking but not selecting in the field).


 onBlur - executed when input focus leaves the field.

 onSelect - executed when the field is input-focused by selecting some

of its text.
 onChange - executed when input focus exits the field and the value of

the field has changed from when onFocus occurred.


 Text area has the same property as text field: the value property. Using
<HTML>
<HEAD>
<TITLE>JavaScript Form Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function add()
{
var op1 = document.test.fnum.value;
var op2 = document.test.snum.value;
var sum = op1 + op2;
document.test.result.value = sum;
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="test" ACTION="" METHOD="GET">
First number: <INPUT TYPE="text" NAME="fnum"><br>
Second number: <INPUT TYPE="text" NAME="snum"><br>
Result: <INPUT TYPE="text" NAME="result"><br>
<INPUT TYPE="button" NAME="adder" Value="Add" onClick="add()">
</FORM>
</BODY>
Form Processing and
Validation…
Checkboxes and Radio Buttons
 To define radio buttons for JavaScript, provide each object with the same

name.
 JavaScript will create an array using the name you've provided; you then

reference the buttons using the array indexes.


 Use the checked property to know the state of the individual radio buttons.

 Radio button has the following properties:

 name - String value of the NAME attribute.

 length - The number of radio buttons in the radio object.

 Value - String value of the VALUE attribute.


 Checked - Boolean value which is true if pressed and false if not pressed.

 defaultChecked - Boolean property that reflects the value of the

CHECKED attribute.
 Type - Specifies what type of object this form field is (e.g. “radio”).
<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function hello () {
var urname = document.test.name.value;
var sex;
if(document.test.sex[0].checked)
sex = document.test.sex[0].value;
else if(document.test.sex[1].checked)
sex = document.test.sex[1].value;
alert ("Hello, " + urname + "! Your are "+sex);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="test" ACTION="" METHOD="GET">
Enter your name: <INPUT TYPE="text" NAME="name" VALUE=""><br>
Sex: <INPUT TYPE="radio" NAME="sex" Value="Male">Male<BR>
<INPUT TYPE="radio" NAME="sex" Value="Female">Female<BR>
<INPUT TYPE="button" NAME="button" Value="Say Hello" onClick="hello()">
</FORM>
</BODY>
Form Processing and
Validation…
Using Selection Lists
 Use the selectedIndex property to test which option item is selected

in the list.
 The item is returned as an index value, with 0 being the first option,

1 being the second, and so forth.


 If no item is selected, the value is -1.

 Select has the following properties in JavaScript:

 length - Contains the number of objects in the select object.

 name - The internal name of the select object as defined by the

NAME attribute.
 selectedIndex - The index number of the currently selected

option of the select object.


Form Processing and
Validation…
 options[] - This property is an object reflecting the contents of the
<OPTION> tag used when defining a select object in HTML.
 It contains the following properties:
 text - String containing the text after the <OPTION> tag. Assigning a

new value to options[index].text will either change the menu item text or
add a new item, in the case of an index higher than the current number of
items.
 Value - Reflection of the VALUE attribute. This is sent to the server when

the Submit button is pressed.


 defaultSelected - Boolean that reflects the SELECTED attribute of the

<OPTION> tag.
 selected - Boolean that indicates the current selected state of the option.

 Event handlers:
 onFocus() - executed when input focus enters the field.
 onBlur ()- executed when input focus leaves the field.
 onChange() - executed when input focus exits the field and the field
<HTML>
<HEAD>
<TITLE>List Box Test</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testSelect () {
var Item = document.test.list.selectedIndex;
result = document.test.list.options[Item].text;
//Or you can use the following line which does the same as the above line
result = document.test.list.value;
alert (result);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME=“test" ACTION="fruits.php" METHOD="GET">
Fruit: <SELECT NAME="list" SIZE="1">
<OPTION>none</OPTION>
<OPTION>Orange</OPTION>
<OPTION>Apple</OPTION>
<OPTION>Papaya</OPTION>
<OPTION>Banana</OPTION>
</SELECT>
<INPUT TYPE="button" NAME="button" value="Test" onClick="testSelect()">
</FORM>
</BODY>
Form Processing and
Validation…
 The form input is often sent back to the server or mailed to a certain
e-mail account.
 But how can you be certain that a valid input was filled by the user?
 With the help of JavaScript the form input can easily be checked
before sending it over the Internet.
 It is sent only if the input is valid.
 Form data that typically are checked by a JavaScript could be:
 has the user left required fields empty?

 has the user entered a valid e-mail address?

 has the user entered a valid date?

 has the user entered text in a numeric field?


<html>
<head>
<script language="JavaScript">
function check(form)
{
if (form.urname.value == "")
alert("Please enter a string as your name!")
if(form.age.value < 0 || form.age.value=="")
alert("Age should be number and greater than 0");
if (form.email.value == "" || form.email.value.indexOf('@', 0) == -1)
alert("No valid e-mail address!");
if(form.urmessage.value=="")
alert("No message written");
}
</script>
</head>
<body>
<h2> <u> Form validation </u> </h2>
<form name="first">
Enter your name: <input type="text" name="urname"> <br>
Enter your age: <input type="text" name="age"> <br>
Enter your e-mail address: <input type="text" name="email"> <br>
write message: <textarea name="urmessage" cols=40 rows=10></textarea><br><br>
<input type="button" name="validate" value="Check Input" onClick="check(this.form)">
</body>

You might also like