Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

AIP Chapter Four

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 138

Chapter 4

JAVASCRIPT

1
JAVASCRIPT
 What is JavaScript?
 JavaScript: the first Web scripting language, developed by
Netscape in 1995 which is syntactically similar to Java/C+
+,
 but simpler & more flexible

 An object-oriented scripting language that is designed


primarily for people who are building web pages using
HTML.
 HTML to define the content of web pages
 CSS to specify the layout of web pages
 JavaScript to program the behavior of web pages

2
CLIENT-SIDE PROGRAMMING
 JavaScriptprograms are embedded within HTML
documents in source code form which is
interpreted by the browser.
 Platform independence
Recall:
 HTML is good for developing static pages
 can specify text/image layout, presentation, links and
specifying the same look for different pages.
 In order to develop interactive/reactive pages, we
must integrate different programming
3
CONT…
 client-side programming:
 programs can be written in a separate programming language
E.g., JavaScript, VBScript
 programs are embedded in the HTML of a Web page, with
tags to identify the program component
e.g., <script type="text/javascript">

</script>
 the browser executes the program as it loads the page,
integrating the dynamic output of the program with the
static content of HTML
4
COMMON SCRIPTING TASKS
JavaScript can perform the following task:
 Decision making (switch and if statements)
 Used in input data validation
 Submitting forms(document.forms["myform"].submit();)
 Performing complex mathematical calculations.
 Adding dynamic features to Web pages
 Image rollovers
 Time-sensitive or random page elements
 utilize
buttons, text boxes, clickable images, prompts, frames
 Can Change HTML Content
 Can Change the value of HTML Attributes
 Can Change HTML styles for a given element 5
JAVASCRIPT AND JAVA
 Although the names resemble quite closely, they are
different languages.
 Some facts:

Both are object-oriented languages.


JavaScript programs are interpreted in source code
form.
Java programs are first compiled into a device
independent byte code format, which is then
interpreted.
JavaScript is a small language and does not have
many features that exist in Java.
Java is a powerful language and can be used in 6
extremely sophisticated applications.
 JavaScript is object-oriented
 It allows interaction with the properties of objects
 Internal built-in objects (e.g. window object).
 Browser objects (e.g. document object).

 JavaScript code can be embedded in a Web page using


SCRIPT tags
◦ the output of JavaScript code is displayed as if directly
entered in HTML
 JavaScript can be placed in the <body> and the <head>
sections of an HTML page.
 In HTML, JavaScript code must be inserted between
<script> and </script> tags.

7
// Java script code inside the head part of our code
<head>
<script>
function myFunction() {
  ---
}</script>
</head>
/ * Javascript code inside the body part of our html code */
<body>
<script>
function myFunction() {
    ----
}</script></body>
// starts a single line comment
/*…*/ enclose multi-line comments 8
EXTERNAL JAVASCRIPT

 Scripts can also be placed in external files.


 External scripts are practical when the same code is used in
many different web pages.
 JavaScript files have the file extension .js.

 To use an external script, put the name of the script file in


the src (source) attribute of the <script> tag:

<script src=“firstscript.js” type="text/javascript">


</script>

9
Advantages External Script:

Separation of HTML code from JavaScript code


It makes HTML and JavaScript easier to read and
maintain
Less code has to be written, and stored.
Commonly used JavaScript code can be shared
among a number of pages.

10
11
JavaScript Function and events
 JavaScript function is a block of JavaScript code, that can be

executed when "asked" for.


For example, a function can be executed when an event occurs,
like when the user clicks a button.
 JavaScript does not have any built-in print or display
functions.
 JavaScript can "display" data in different ways:
 Writing into an alert box, using window.alert().
<script>
window.alert(“ Please fill the form!!”);
</script>

12
 Writing into the HTML output using document.write()
 <script>
document.write(5 + 6);
</script>
 Writing into an HTML element, using innerHTML
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =“Hello
Javascript”;
</script>

13
EXAMPLE
<html>
<head>
<title>JavaScript Page</title>
</head>
<body>
<script type="text/javascript">
document.write("Hello world!");
document.write("<p>How are <br />"
+"<i>you</i>?</p>");
</script>
<p>Here is some static text as well.
</p></body>
</html>

14
JAVASCRIPT SYNTAX
JavaScript syntax is the rules, how JavaScript programs are
constructed.
JavaScript statements are separated by semicolon:

var x = 5; var y = 6;


var z = x + y;
The var keyword tells the browser to create a new variable
JavaScript statements are composed of: Values, Operators,
Expressions, Keywords, and Comments.
The JavaScript syntax defines two types of values: Fixed
values and variable values.
Fixed values are called literals. Variable values are
called variables.
15
JavaScript Operators

 JavaScript uses an assignment operator ( = ) to assign values


to variables:
var x = 5;
var y = 6;
 JavaScript uses arithmetic operators ( + - *  / )
to compute values:
(5 + 6) * 10
 JavaScript Keywords- are used to identify actions to be
performed.
E.g. The var keyword tells the browser to create a new variable:
var x = 5 + 6;
var y = x * 10;
16
JavaScript uses the var keyword to define variables.
 Code after double slashes // or between /* and */ is treated as
a comment.
 Comments are ignored, and will not be executed:

var x = 5;   // I will be executed


// var x = 6;   I will NOT be executed
 JavaScript is Case Sensitive- all JavaScript identifiers
are case sensitive. 
 The variables lastName and lastname, are two different
variables.
lastName = “Abel";
lastname = “Selam";
 JavaScript does not interpret VAR or Var as the keyword var.

17
JAVASCRIPT STATEMENTS
 In HTML, JavaScript statements are "instructions" to be
"executed" by the web browser.
 Example

document.getElementById("demo").innerHTML = "Hello
John.";
 This statement tells the browser to write "Hello John."
inside an HTML element with id="demo":
 Statements are executed, one by one, in the same order as they
are written.
 Example var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z; 18
 In this example, x, y, and z is given values, and finally z is
displayed:
 JavaScript statements are separated by semicolon
E.g var a = 5;
var b = 6;
 You can declare many variables in one statement-start the
statement with var and separate the variables by comma:
E.g
var person = "John Doe", carName = "Volvo;
 JavaScript ignores multiple spaces. You can add white space to
your script to make it more readable.

19
JAVASCRIPT VARIABLES

 JavaScript variables are containers for storing data values.


 Example

var x = 5;
var y = 6;
var z = x + y;/* In this example, x, y, and z, are variables */
 All JavaScript variables must be identified  with unique
names called identifiers.
 Identifiers can be short names (like x and y), or more
descriptive names (age, sum, totalmark).

20
The general rules for constructing names for variables (unique
identifiers) are:
 Names can contain letters, digits, underscores, and dollar signs.

 Names must begin with a letter , $ (dollar sign) or _(underscore)

 Names are case sensitive (y and Y are different variables)

 Reserved words (like JavaScript keywords) cannot be used as


names

21
JAVASCRIPT DATA TYPES
 In programming, data types is an important concept.
 To be able to operate on variables, it is important to know
something about the type.
 Without data types, a computer cannot safely solve this: var x
= 16 + "Volvo"
 Does it make any sense to add "Volvo" to sixteen? Will
produce an error or a result?
 JavaScript has three primitive data types
 strings : "foo" 'howdy do' "I said 'hi'." ""
 numbers : 12 3.14159 1.5E6
 booleans : true false

 JavaScript variables can hold numbers like 100, and text values
like “Hello JS". 22
 In programming, text values are called text strings.
 Strings are written inside double or single quotes.

E.g
var carName = "Volvo XC60";   // Using double quotes
var carName = 'Volvo XC60';   // Using single quotes
 You can use quotes inside a string, as long as they don't match
the quotes surrounding the string:
var answer = "It's alright"; // Single quote inside double quotes
var answer = "He is called 'Johnny'"; // Single quotes inside
double quotes
var answer = 'He is called "Johnny "';  // Double quotes inside
single quotes

23
 JavaScript has only one type of numbers which can be written with, or
without decimals:
 Example

var x1 = 34.00;     // Written with decimals


var x2 = 34;        // Written without decimals
 Extra large or extra small numbers can be written with scientific
(exponential) notation:
 Example

var y = 123e5;      // 12300000


var z = 123e-5;     // 0.00123
 JavaScript has dynamic types. This means that the same variable can be
used as different types:
 Example

var x;               // Now x is undefined


var x = 5;           // Now x is a Number
var x = "John";      // Now x is a String
24
 JavaScript Booleans have two values: true or false.
 Example

var x = true; var y = false;


//Booleans are often used in conditional testing.
JavaScript Arrays
 are written with square brackets in which the items are
separated by comma;
 The following code declares (creates) an array called cars,
containing three items (car names):
 Example

var cars = ["Saab", "Volvo", "BMW"];
 Arrays use numbers to access its elements.

e.g cars[0]//return Saab 25


ARRAY CONT.…..
 JavaScript objects are written with curly braces.
 Object properties are written as name:value pairs, separated
by commas.
 Example

var person = {firstName:"John", lastName:"Doe", age:50,


eyeColor:"blue"};
 The object (person) in the example above has 4 properties:
firstName, lastName, age, and eyeColor.
 JavaScript uses names to access object properties.

document.write(person.firstName);//return John

26
 In JavaScript we can use the JavaScript typeof
 operator to find the type of a JavaScript variable:
 Example

typeof  "John"             // Returns string 


typeof  3.14                  // Returns number
typeof  false                 // Returns boolean
typeof  {name:'John', age:34} // Returns object
 In JavaScript, a variable without a value is undefined.

 Example

var person;  // Value is undefined, typeof is also undefined

27
JAVASCRIPT FUNCTION
 A JavaScript function is a block of code designed to perform
a particular task.
 A JavaScript function is defined with the function keyword,
followed by a name, followed by parentheses ().
 Example

function myFunction(p1, p2) {
    return p1 * p2;  // the function returns the product of p1 and p2
}
 A JavaScript function is executed when "something" invokes
it (calls it).

28
 Function names can contain letters, digits, underscores, and
dollar signs (same rules as variables).
 The parentheses may include parameter names separated by
commas: (parameter1, parameter2, ...)
 The code to be executed, by the function, is placed inside
curly brackets: {}
 functionName(parameter1, parameter2, parameter3)

{
    code to be executed
}

29
JAVASCRIPT TERMINOLOGY

 Understanding JavaScript terms is fundamental to


understanding the script.
 Objects, Properties, Methods, Events, Functions, Values,
Variables, Expressions, Operators.

30
OBJECTS
 Objects refers to windows, documents, images, tables,
forms, buttons or links, etc.

 Objects have properties that act as modifiers.

31
PROPERTIES
 Properties are object attributes.
 Object properties are defined by using the object's name,
a period, and the property name.
 e.g.,background color is expressed by: document.bgColor
= “lightblue";
 document is the object.
 bgcolor is the property.

32
METHODS
 Methods are actions applied to particular objects.
 Methods are what objects can do.
 e.g., document.write(”Hello World")
 document is the object.
 write is the method.

33
DOCUMENT.WRITE(“STRING”)
<HTML>
<HEAD><TITLE>Hello!</TITLE></HEAD>
<BODY>
<H1> First JavaScript Page </H1>
<SCRIPT TYPE="text/javascript">
document.write("<HR/>");
document.write("Hello WWW!");
document.write("<HR/>");
document.bgColor = “lightblue";
</SCRIPT>
</BODY>
</HTML>

34
EVENTS
 Events associate an object with an action.
 e.g., the OnMouseover event handler action can change an
image.
 e.g., the onSubmit event handler sends a form.
 onClick

 User actions events- occur when the user performs a


certain action like mouse click or mouse over, to perform
different tasks.

35
EVENTS…
 JavaScript defines various events:
 onClick – when a link or image is clicked
 onSubmit -a form is submitted
 onMouseOver -the mouse cursor moves over it
 onChange-when the content of a form element, the
selection, or the checked state have changed.
 onLoad -something gets loaded in the browser
 etc.
 Events are specified in the HTML code.

36
EVENT EXAMPLE
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body>
</html>
37
FUNCTIONS

 Functions are named statements that performs different


task.
 e.g.,
function doWhatever ()
{
statement here
}
 The curly braces contain the statements of the function.

 JavaScript has built-in functions, and you can write


your own.
 E.g

String()- converts the object argument passed to it to a string


value.
38
Date()- return todays date
VALUES
 Values are bits of information.
 Values types include
 Number: 1, 2, 3, etc.
 String: characters enclosed in quotes.
 Boolean: true or false.
 Object: image, form
 Function: validate, doWhatever

39
VARIABLES

 Variables contain values and use the equal sign to specify


their value.
 Variables are created by declaration using the var
command with or without an initial value state.
 e.g. var month;
 e.g. var month = “April’;
 e.g. month = “April”;

40
EXPRESSIONS

 Expressions are commands that assign values to


variables.
 Expressions always use an assignment operator to assign
a value to variables.
 e.g., var month = “May”; is an expression.
 Expressions end with a semicolon .

41
ALERT BOX
 An alert box is often used if you want to make sure
information comes through to the user.
 When an alert box pops up, the user will have to
click "OK" to proceed.
 The message is specified within parenthesis.

Syntax: alert("sometext");
 The following script in the <body> tag uses the
onLoad event to display an Alert window

42
EXAMPLE
<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
</head>
<body onload="show_alert()" value="Show alert box">
</body>
</html>
43
PROMPT BOX
• A prompt box is often used if you want the user to input a
value.
• When a prompt box pops up, the user will have to click either
"OK" or "Cancel" to proceed after entering an input value.
• If the user clicks "OK" the box returns the input value.
• If the user clicks "Cancel" the box returns null.
• Syntax: prompt(“message text","defaultvalue");
 1st argument: the prompt message that appears in the dialog
box
 2nd argument: a default value that will appear in the box (in
case the user enters nothing)
44
EXAMPLE 1
<html><head>
<script type="text/javascript">
<!--
function prompter() {
var reply = prompt("Hey there, good looking stranger! What's your
name?", "")
alert ( "Nice to see you around these parts " + reply + "!")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="prompter()" value="Say my
name!">
</body> </html> 45
EXAMPLE 2
<html> <head>
<title>Interactive page</title>
</head> <body>
<script type="text/javascript">
userName = prompt("What is your name?", "");
userAge = prompt("Your age?", "");
userAge = parseFloat(userAge);
document.write("Hello " + userName + ".")
if (userAge < 18) {
document.write(" Do your parents know " + "you are
online?");
}
</script>
<p>The rest of the page...
</body> </html> 46
JAVASCRIPT CONFIRM BOX

 A Javascript confirmation box is a way to give the


visitor a choice of whether or not an action to be
performed.
 When a confirm box pops up, the user will have to
click either "OK" or "Cancel" to proceed.
 If the user clicks "OK", the box returns true. If the
user clicks "Cancel", the box returns false.
 Syntax: confirm (“The question to ask …”);

47
EXAMPLE
<html> <head>
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Press a button");
if (r==true)
 {
  alert("You pressed OK!");
 }
else
 {
  alert("You pressed Cancel!");
 }
}
</script>
</head> <body>
<input type="button" onclick="show_confirm()" value="Show
confirm box" />
48
</body> </html>
JAVASCRIPT FUNCTIONS
 JavaScript function is a block of code (group of statements)
designed to perform a particular task.
 A JavaScript function is defined with the function keyword,
followed by a name, followed by parentheses ()
function function_name(parameters)
{
JavaScript commands
}
 parameters are the values sent to the function (note: not all
functions require parameters)
{ and } are used to mark the beginning and end of the
commands in the function. 49
CREATING JAVASCRIPT FUNCTIONS
 Function names are case-sensitive.
 Function names can contain letters, digits, underscores,
and dollar signs.
 The function name must begin with a letter or underscore
( _ ) and cannot contain any spaces.
 There is no limit to the number of function parameters that
a function may contain.
 The parentheses may include parameter names separated
by commas: (parameter1, parameter2, ...)
 The code to be executed, by the function, is placed inside
curly brackets: {}
 Function arguments are the real values received by the
function when it is invoked 50
PERFORMING AN ACTION WITH A FUNCTION
Function Definition
function ShowDate(date) {
document.write(“Today is” + date + “<br>”);
}
Function Call
 The code inside the function will execute when
"something" invokes the function:
 When an event occurs (when a user clicks a button), called from
JavaScript code or self-invoking.
 If a function is called with missing arguments (less than
declared), the missing values are set to: undefined.
var Today = date(); // Variable declaraion
ShowDate(Today); // function call with arguments 51
FUNCTION RETURN
 When JavaScript reaches a return statement, the function will stop
executing
 The return value of a function is "returned" back to the "caller":

E.g
function Area(Width, Length)
{
var Size = Width*Length; // calculate the area and assigned it size
return Size; // return the result to its caller statement
}
var area= Area (4, 3); // function is called, return value will end up in
area

52
PLACING A FUNCTION IN AN HTML FILE
 The function definition must be placed before the
command that calls the function.
 One convention is to place all of the function definitions
in the <head> section.
 A function is executed only when called by another
JavaScript command.

53
WORKING WITH CONDITIONAL STATEMENTS
Comparison, Logical and Conditional Operators

To create a condition, you need one of the three types of operators:


 a comparison operator compares the value of one element
with that of another, which creates a Boolean expression that
is either true or false
 a logical operator connects two or more Boolean expressions
 a conditional operator tests whether a specific condition is
true and returns one value if the condition is true and a
different value if the condition is false

54
AN EXAMPLE OF BOOLEAN EXPRESSIONS

 x < 100;
 if x is less than 100, this expression returns the value
true; however, if x is 100 or greater, the expression is
false
 y == 20;

 the y variable must have an exact value of 20 for the


expression to be true
 comparison operator uses a double equal sign (==)

55
COMPARISON OPERATORS
Operator Description
== Returns true if variable are equal (x==y)

!= Return true if variable are not equal (x!=y)

> Return true of the value on the left is greater than the right
one(x>y)

< Return true if the variable on the left is less than the right
one(x<y)
>= Return true if the variable on the left is greater than or
equal to the right one(x>=y)

<= Return true if the variable on the left is less than or equal to
the right one (x<=y)

56
A LOGICAL OPERATOR
 The logical operator && returns a value of true only if all
of the Boolean expressions are true.
Operator Description Examples
Let the value of x=20 and y=25

&& Return true when both (x==20) && (y==25) returns true
expressions are true (x==20 && y==20) returns false

|| Return true when one of (x==20) || (y==25) returns true


the expression is true (x==20 || y==20) returns false

! Return true if the !(x==20) returns false


expression is false and !(x==25) returns true
false if the expression is
true 57
A CONDITIONAL OPERATOR
 Conditional operator tests whether a specific condition is true
and returns one value if the condition is true and a different
value if the condition is false.
Syntax:
variable_name=(condition)?value1:value2;
 E.g

Message = (mail == “Yes”) ? “You have mail”: “No mail”;


 tests whether the mail variable is equal to the value “Yes”
 if it is, the Message variable has the value “You have
mail”;
 otherwise, the Message variable has the value “No mail”.

58
WORKING WITH CONDITIONAL STATEMENTS
 Conditional statements are used to perform different
actions based on different conditions.
JavaScript has the following conditional statements

if statement: use this statement to execute some code


only if a specified condition is true.
if...else statement: use this statement to execute some
code if the condition is true and another code if the
condition is false
if...else if....else statement: use this statement to select
one of many blocks of code to be executed .
switch statement: use this statement to select one of
many blocks of code to be executed.
59
JAVASCRIPT IF STATEMENT

 Use if statement to execute some code only if a specified


condition is true
Syntax:
if (condition)
{
JavaScript Commands
}
condition is an expression that is either true or false
If the condition is true, the JavaScript Commands in
the command block are executed
If the condition is not true, then no action is taken
60
EXAMPLE
<html>
<body>
<p>This example demonstrates the If statement.</p>
<script type="text/javascript">
var d = new Date();
var time = d.getHours();
if (time < 10)
{
document.write("<b>Good morning</b>");
}
</script>
<p>If the time on your browser is less than 10, you will get a
"Good morning" greeting.</p>
</body>
</html> 61
JAVASCRIPT IF-ELSE STATEMENT
 Use if ….else statement to execute some code if a condition is true
and another code if the condition is false
Syntax:
if (condition) {
    block of code to be executed if the condition is true
} else { 
    block of code to be executed if the condition is false
}
 If the condition is true, the JavaScript Commands in the
command block are executed
 If the condition is not true, then else part will be
executed 62
EXAMPLE
<html>
<body>
<p>This example demonstrates the If…else statement.</p>
<script type="text/javascript">
var d = new Date();
var time = d.getHours();
if (time < 10)
{
document.write("<b>Good morning</b>");
}
else{
document.write("<b>Good Afternoon</b>");
}
</script>
<p>If the time on your browser is less than 10,
you will get a "Good morning" greeting.
Otherwise you will get a "Good day" greeting.</p> 63
</body>
</html>
JAVASCRIPT IF...ELSE IF...ELSE STATEMENT
 Use the if....else if...else statement to select one of several
blocks of code to be executed.
Syntax:
if (condition1) {
    block of code to be executed if condition1 is true
} else if (condition2) {
    block of code to be executed if the condition1 is false and condition2
is true
}
…..
else {
    block of code to be executed if the condition1 is false and condition2
is false
}
// If condition1 is true then the 1st block of code will be executed
// If condition1 is false and condition2 is true then the 2nd block of code
will be executed
otherwise the 3rd block of code will be executed 64
EXAMPLE
<html>
<body>
<script type="text/javascript">
var d = new Date();
var time = d.getHours();
if (time<10){
document.write("<b>Good morning</b>");
}
else if (time>=10 && time<16){
document.write("<b>Good Afternoon</b>");
}
else{
document.write("<b>Hello World!</b>");
}
</script>
<p>
This example demonstrates the if..else if...else statement.</p> 65
</body>
</html>
JAVASCRIPT SWITCH STATEMENT
 The switch statement is used to perform different action based on
different conditions
 Use the switch statement to select one of many blocks of code to be
executed.
switch(expression) {
    case n:
        code block
        break;
    case n:
        code block
        break;
    default:
        default code block
}
 The switch expression is evaluated once.
 The value of the expression is compared with the values of each
case.
 If there is a match, the associated block of code is executed. 66
EXAMPLE
<script type="text/javascript">
switch (new Date().getDay())
{
 case 0: day = "Sunday";
   break;
 case 1:day = "Monday";
     break;
case 2: day = "Tuesday";
      break;
case 3: day = "Wednesday";
       break;
case 4: day = "Thursday";
   break;
case 5: day = "Friday";
       break;
case 6: day = "Saturday";
      break;
}
document.write(new Date().getDay()); 67
document.write("<br>"+day);
</script>
WORKING WITH LOOPS
 A program loop is a set of instructions that is
executed repeatedly.
 Loops execute a block of code a specified number
of times or while a specified condition is true.
 There are two types of loops:
 For: loops through a block of code for a specified number
of times (loops that repeat a number of times before
quitting)
 While: loops through a block of code while a specified
condition is true (loops that repeat as long as a certain
condition is met)

68
THE FOR LOOP
 The For loop allows you to create a group of commands to be
executed a number of times through the use of a counter that tracks
the number of times the command block has been run.
 Syntax:
for (start; condition; update)
{
JavaScript Commands
}
 start is the starting value of the counter
 condition is a Boolean expression that must be true for the loop to
continue
 update specifies how the counter changes in value each time the
command block is executed
 Set an initial value for the counter, and each time the command block
is executed, the counter changes in value.
 When the counter reaches a value above or below a certain stopping
value, the loop ends. 69
EXAMPLE

<html>
<body>
<script type="text/javascript">
for (i = 1; i <= 6; i++)
{
document.write("<h" + i + ">This is heading " + i);
document.write("</h" + i + ">");
}
</script>
</body>
</html> 70
EXAMPLE 2
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var cars = ["BMW", "Volvo", "Saab", "Ford"];
text = "";
for (var i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body> 71
</html>
EXAMPLE 3
<html>
<body>
<table border="1px">
<tr>
<script>
for(var num=1; num<=5; num++){
document.write("<td>"+ num +"</td>");
}
</script>
</tr>
</table>
</body>
72
</html>
NESTED FOR EXAMPLE
<html>
<body><table border="1px"><tr>
<script>
var rownum, colnum;
for(rownum=1; rownum<=3; rownum++){
document.write("<tr>");
for(colnum=1; colnum<=4; colnum++){
document.write("<td>"+ rownum + "," + colnum +"</td>");
}
document.write("</tr>");
}
</script></tr></table></body>
73
</html>
FOR IN LOOP
 for/in - loops through the properties of an object
E.g
<html>
<body><p id="demo"></p>
<script>
var txt = ""; var x;
var person = {fname:“Sam", lname:“Abebe", age:25};
for (x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script> 74
</body> </html>
THE WHILE LOOP
 The While loop runs a command group as long as a specific
condition is met, but it does not employ any counters.
 Loops through a block of code a specified number of times or
while a specified condition is true.
 The general syntax of the While loop is:

while (condition)
{
JavaScript Commands
}
 condition is a Boolean expression that can be either true or
false

75
EXAMPLE
<html>
<body>
<table border="1px">
<tr>
<script>
var num=1;
while(num<=5){
document.write("<td>"+ num +"</td>");
num++;
}
</script></tr>
</table></body>
76
</html>
EXAMPLE 2

<html>
<body>
<table border="1px"> <tr><script>
var rownum=1, colnum=1;
while(rownum<=3) {
document.write("<tr>");
while(colnum<=4){
document.write("<td>"+ rownum + "," + colnum +"</td>");
colnum++;
}
document.write("</tr>");
rownum++; colnum=1; 77
}</script></tr></table></body></html>
USING ARRAYS
 JavaScript arrays are used to store multiple values in a single
variable(an ordered collection of values referenced by a single
variable name).
 Syntax:
 Using the JavaScript new keyword

var array-name = new Array(size);


 size is the number of elements in the array (optional)
 To assign value to array elements, use:
array-name[i]=value; where i is the index of the array item.
The 1st item has an index value of 0.
Or
 Using array literal(easiest and fast way)
var array-name = [item1, item2, ...];  78
EXAMPLE
<html><head><title> Javascript array</title>
</head><body><script>
var fruits= new Array();
fruits[0]="Apple"; fruits[1]="Mango"; fruits[2]="Orange";
document.write("<h3>"+" The fruits I like most:"+"</h3>");
document.write("<ul>");
for (var i = 0; i < fruits.length; i++) {
document.write("<li>"+fruits[i] + "</li>");
}
document.write("</ul>");
</script> 79

</body></html>
ARRAY DECLARATION AND ASSIGNMENT WITHIN ONE
LINE
<body><script>
var MonthTxt=[ "January", "February", "March", "April",
"May","June", "July", "August", "September", "October",
"November", "December“];
document.write("<h3>"+" Months of the year are:"+"</h3>");
document.write("<ul>");
for (var i = 0; i < MonthTxt.length; i++) {
document.write("<li>"+MonthTxt[i] + "</li>");
}
document.write("</ul>");
</script>
</body> 80
// we can use array() or array[] in array declaration and assignment
JAVASCRIPT OBJECTS AND METHODS
 In the context of JavaScript:
◦ An object is a collection of properties and methods which can be
viewed, modified and interacted with.
 A simple example of property is color, which is rather easy to
visualize.
 They can be directly manipulated by referring to the object and the

property by name and then setting its value.


 For example, the background color of a page can be changed as:

document.bgColor = “lightblue”;
document.fgColor = “green”;
 In the object-oriented paradigm, methods refer to functions that can be
used to manipulate objects and their properties.
 Example:
The method write(), which when invoked on the document object, causes a
specific string of characters to be outputted.
document.write (“Hello Good Day”);
window.alert(“This is an alert!!”); 81
CONT…
 Methods which are defined on an object give the range of choices
available for interacting with the object.
 Some examples:
 A window object can be opened or closed using the open() and close()
methods respectively.
 A form object has a submit() method which transmits the contents of
the form to the web server.
 The sequential list of a user’s path through a number of URLs is
represented by the history object, which has forward() and
backward() methods to move through the list.
 Apart from the pre-defined methods, it is also possible to create
user-defined methods.
◦ Control the rate with which a line of text scrolls across the screen.
◦ Determine the path of an animated object across the display.
82
DATA VALIDATION
 JavaScript can be used for client-side validation of data
entered in HTML forms.
 Dataentered can be extracted and accessed.
 Checks can be made on the data entered.
 Non-alphabetic characters in name.
 Non-numeric characters in roll number, age, etc.

 Bid amount less than minimum permissible.

 A data validation example:


 A student registration form.
 A function checks whether the input is empty or not
 Invoked when the form is submitted.
 Check performed before form data are transmitted to server-

side application.
83
EXAMPLE
<html><head>
<script type="text/javascript">
function validate(){
if( document.myForm.fName.value == "" ){
alert( "Please provide your First name!" );
document.myForm.fName.focus() ;
return false;}
if( document.myForm.lName.value == "" ){
alert( "Please provide your Last name!" );
document.myForm.lName.focus() ;
return false; }
if( document.myForm.email.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.email.focus() ;
return false;} 84
return(true);} </script> </head>
<body>
<H3> Student Registration Form </H3>
<form action="registration.php" name="myForm"
onsubmit="return(validate());">
<p>First Name:<input type="text" name="fName" /></p>
<p>Father Name:<input type="text" name="lName" /></p>
<p>Email Address:<input type="text" name="email" /></p>
<p>Phone Number:<input type="text" name="phone"/></p>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body> 85
</html>
SIMPLE ANIMATION
 JavaScript provides following two functions to be frequently
used in animation programs.
 setTimeout(function,duration,param1,param2,..)
 Schedules a piece of Javascript code to run at some specified time
in the future.
 Time specified in milliseconds.

 Commonly used to perform animation or other kinds of repetitive

operations.
 setInterval(function,duration,param1,param2,..)
 This function calls a function after every duration of milliseconds.
 clearTimeout(setTimeout_variable) - This function call clears
any timer set by the setTimeout() functions.
86
EXAMPLE
<script type="text/javascript">
var imgObj = null;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight(){
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
}
window.onload =init;
</script> 87
</head>
<body onload="setInterval(moveRight,200);">
<form>
<img id="myImage" src="1.gif" width="100"
height="100"/>
</form>
</body>
</html>

88
EXAMPLE

<html><head>
<script type="text/javascript">
function mouseOver(){
document.getElementById("btn1").src ="button_blue.gif";
}
function mouseOut(){
document.getElementById("btn1").src ="button_pink.gif";
}</script>
</head>
<body>
<a href="www.mau.edu.et" target="_blank">
<img border="0" alt="Mekdela Amba University" src="b_pink.gif" id="btn1"
width="26" height="26" onmouseover="mouseOver()"
onmouseout="mouseOut()" /></a>
89
</body></html>
HISTORY BACK / FORWARD
 Contains the URLs visited by the user (within a browser window).
 Uses the back() and forward() methods to scroll through the
recently visited pages.
 history.back()- same as clicking back in the browser
 history.forward() - same as clicking forward in the browser

E.g Index.html
<html>
<body>
<h1>Index page</h1>
<br/>
<a href="news.html">News</a>
</body>
</html> 90
News.html
<html>
<body>
<h1>News page</h1>
<a href="newsdetail.html">News Detail</a>
<br/>
<br/>
<button onclick="window.history.back()">Go Back
</button>
<button onclick="window.history.forward()"> Go
forward</button>
</body>
</html> 91
Newsdetail.html
<html>
<body>
<h1>News Detail page</h1>
<br/>
<button onclick="window.history.back()">Go
Back</button>
</body>
</html>
 Once you are on the news page, you can go back to the
index page by using window.history.back and to the news
detail page by using windwo.history.forward method

92
BROWSER DETECTION
 This feature allows one to find out what type of browser
is being used.
 There are two objects used for this:
 navigator.appName : returns the name of the browser.
 navigator.appVersion : returns the version of the browser.

93
EXAMPLE: BROWSER DETECTION
<html><head>
</head>
<body>
<script type="text/javascript">
var browserName = navigator.appName;
var browserVersion = navigator.appVersion;
if (browserName=="Netscape")
alert("Hi Netscape User!" + browserVersion);
else
if (browserName=="Microsoft Internet Explorer")
alert("Hi, Explorer User!" + browserVersion);
else
alert("Unrecognized browser!");
</SCRIPT>
</body>
</html> 94
PAGE REDIRECTION

 Commonly used feature.


 A previously existing web site might have moved to a new location.
 You may want the request to be redirected to a site depending on the
browser type and version.
 Manipulate the window.location attribute.

 An example follows.
 Will take us to a page after 5 seconds.
 Example
<script>
function getgoing (){
window.location = "http://www.mau.edu.et";
}
alert( "You will be redirected in five seconds."); 95
setTimeout ('getgoing()', 5000); </script >
CREATING NEW BROWSER WINDOW
 To open a new window, we need to call the window.open()
method.
 window.open (‘url to open’, ‘window name’, attribute1,
attribute2, …);
 Window attributes:
 width = 300
 height = 200

 resizable = yes or no

 scrollbars = yes or no

 toolbars = yes or no

 status = yes or no

 menubar = yes or no

 copyhistory = yes or no

 An example is shown with some of the attributes.


96
EXAMPLE: NEW WINDOW
<html><head>
</head>
</head>
<body>
<FORM>
<INPUT type="button" value="New Window!"
onClick="window.open('http://www.mau.edu.et',
'mywindow','width=400', 'height=200',
'toolbar=yes', 'status=yes')">
</FORM>
</body> 97
</html>
JAVASCRIPT LANGUAGE OBJECTS
 JavaScript is a programming language with strong object-oriented
capabilities.
 An object oriented language enables you to model data using objects
consisting of properties and methods that operate on those properties.
 Properties are the values associated with an object.
E.g The length property of the string object returns the number of
characters in a string
var txt="Hello World!";
document.write(txt.length); // accessing the property of an object
document.write(txt["length"]); //accessing the property of an object
 Methods are the actions that can be performed on objects
E.g var str="Hello world!";
document.write(str.toUpperCase());

98
• JavaScript supports the following built-in language objects:
• The String object
• The Array object
• The Date object
• The Math object
• e.t.c
String Object
• The String Object
• The string object used to manipulate a stored piece of text.
• Can be created by assigning a string value to a variable or a property.
• Syntax: var x=new String(string here);
e.g var y = new String("John");)
• JavaScript’s string and character are appropriate for processing names,
addresses, credit card information, etc.
 Characters
 Fundamental building blocks of JavaScript strings
 String
 Series of characters treated as a single unit 99
Method Description
METHODS OF THE STRING OBJECT
charAt(index) Returns a string containing the character at the specified index.
If there is no character at the index, it returns an empty string.
The first character located at index 0 e.g var str = "HELLO
WORLD";
var res = str.charAt(0)
charCodeAt(indext) Returns the Unicode value of the character at the specified
index. If there is no character at the index. charCodeAt ruturns
NaN(not a number)
concat(string) Concatenate its argument to the end of the string that involves
the method.
E.g s1.concat(s2); is the same as s1+s2;
fromCharcode(val1,val Converts a Unicode values into a string concatenating the
2, …) corresponding character
e.gvar res = String.fromCharCode(65);// return A
indexOf(substrin, start) Returns the position of the first found occurrence of a specified
value in a string
var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");// return 13
100
lastIndexOf(subsring, Returns the position of the last found occurrence of a specified
start) value in a string
Method Description
METHODS OF THE STRING
slice(start,end)
OBJECT
Returns a string containing the portion of the string from
index start to index end.
var res = str.slice(0, 5);//return hello
split(string) Split the source string into an array of string where its string
argument specifies the delimiter
str.split(" ");//HELLO, WORLD
substr(start,length) Returns the string containing length characters starting from
index starting the source string. If length is not specified , a
sting containing characters from start to the end of the source
string is returned
substring(start,end) Returns a string containing a character from index start up but
not including index end in the source string. var res =
str.substring(1, 4);// return ELL
toLowerCase() Returns a string in which all upper case letters are converted to
lowercase case letters. Non character strings are not converted

toUpperCase() Returns a string in which all lower case letters are converted to
upper case letters. Non character strings are not converted

toString() Returns the same string as the source string.


101
var res = str.toString();
valueOf() Returns the same string as the source string
var res = str.valueOf();
ARRAY OBJECT
• The Array object let's you store multiple values in a single variable
E.g var fruits = new Array( "apple", "orange", "mango" );
var fruits = [ "apple", "orange", "mango" ];
• Methods associated with the array object are as follows:
• concat(): returns a new array comprised of this array joined with other array(s).
E.g fruits.concat(otherarray)
• join: joins the elements of an array into a string, and returns the string separated
by the specified. Example: fruits.join(" * ");
• pop(): removes the last element from an array and display the array
Example: fruits.pop();// Removes the last element ("Mango") from fruits

• push(): adds one or more elements to the end of an array and returns the
elements of the new array size.Ex: fruits.push(“potato");
• 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. e.g: fruits.shift();
• unshift(): adds one or more elements to the front of an array and returns the new
102
length of the array. E.g:fruits.unshift("Lemon");
THE MATH OBJECT & MATH METHODS
 The Math object allows you to perform mathematical tasks.
 Includes several mathematical constants and methods.

 way of performing a calculation using the JavaScript built-in


Math methods.
 These methods are applied to an object called the Math object.

 The syntax for applying a Math method is:

value = Math.method(variable);
 For example,
AbsValue = Math.abs(NumVar);
var pi_value=Math.PI;
var sqrt_value=Math.sqrt(16);

103
Math Method Descrition
Math.abs(number) Returns the absolute value of number

Math.sin(number) Calculate the sine of number, where number is an angel


expressed in radians

Math.cos(number) Calculate the cosine of number, where number is an


angel expressed in radians

Math.round(number) Rounds number to the closest integer

Math.ceil(number) Rounds number up to the next highest integer

Math.floor(number) Rounds number down to the next lowest integer

Math.random() Return a random number between 0 and 1 104


 the Math object contains functions and constants
 abs(x): Returns the absolute value of x
 acos(x) :Returns the arccosine of x, in radians
 asin(x):Returns the arcsine of x, in radians
 atan(x):Returns the arctangent of x as a numeric value
between -PI/2 and PI/2 radians
 ceil(x):Returns x, rounded upwards to the nearest integer
 cos(x):Returns the cosine of x (x is in radians)
 sin(x):Returns the sine of x (x is in radians)

105
CONT…
 exp(x) : Returns the value of Ex
 floor(x): Returns x, rounded downwards to the nearest integer
 log(x):Returns the natural logarithm (base E) of x
 max(x,y,z,...,n) :Returns the number with the highest
value
 min(x,y,z,...,n):Returns the number with the lowest value
 pow(x,y):Returns the value of x to the power of y
 random() :Returns a random number between 0 and 1
 round(x):Rounds x to the nearest integer
 sqrt(x):Returns the square root of x
 tan(x):Returns the tangent of an angle

106
DATE OBJECT

• The Date object is a data type built into the JavaScript


language.
• Provides methods for date and time manipulations
• Once a Date object is created, a number of methods allow you
to operate on it.
• Date objects are created with the new Date( )
E.g
var d = new Date();
var d = new Date(dateString);
var d= new Date(year, month, day, hours, minutes, seconds
, milliseconds);
• Most methods simply allow you to get and set the year,
month, day, hour, minute, second, and millisecond fields of
the object, using either local time or UTC (universal, or GMT)
107
time.
Me thod De sc ription
getDate() Returns a number from 1 to 31 representing the day of the month in local time or UTC, respectively.(የዛሬውን
getUTCDate() ቀን 1-31)

getDay() Returns a number from 0 (Sunday) to 6 (Saturday) representing the day of the week in local time or UTC,
getUTCDay() respectively.ዓ.ም በኢሮፓውያን

getFullYear() Returns the year as a four-digit number in local time or UTC, respectively.
getUTCFullYear()
getHours() Returns a number from 0 to 23 representing hours since midnight in local time or UTC, respectively.
getUTCHours()
getMilliseconds() Returns a number from 0 to 999 representing the number of milliseconds in local time or UTC, respectively.
getUTCMilliSeconds() The time is stored in hours, minutes, seconds and milliseconds.

getMinutes() Returns a number from 0 to 59 representing the minutes for the time in local time or UTC, respectively.
getUTCMinutes()
getMonth() Returns a number from 0 (January) to 11 (December) representing the month in local time or UTC,
getUTCMonth() respectively.
getSeconds() Returns a number from 0 to 59 representing the seconds for the time in local time or UTC, respectively.
getUTCSeconds()
getTime() Returns the number of milliseconds between January 1, 1970 and the time in the Date object.

getTimezoneOffset() Returns the difference in minutes between the current time on the local computer and UTC—previously
known as Greenwich Mean Time (GMT).

108
setDate( val ) Sets the day of the month (1 to 31) in local time or UTC, respectively.
setUTCDate( val )
METHODS OF THE DATE OBJECT…..
Me tho d De sc riptio n
setFullYear( y, m, d ) Sets the year in local time or UTC, respectively. The second and third
arguments representing the month and the date are optional. If an optional
setUTCFullYear( y, m, d ) argument is not specified, the current value in the Date object is used.

setHours( h, m, s, ms ) Sets the hour in local time or UTC, respectively. The second, third and fourth
arguments representing the minutes, seconds and milliseconds are optional. If
setUTCHours( h, m, s, ms ) an optional argument is not specified, the current value in the Date object is
used.

setMilliSeconds( ms ) Sets the number of milliseconds in local time or UTC, respectively.


setUTCMilliseconds( ms )
setMinutes( m, s, ms ) Sets the minute in local time or UTC, respectively. The second and third
arguments representing the seconds and milliseconds are optional. If an
setUTCMinutes( m, s, ms ) optional argument is not specified, the current value in the Date object is
used.

setMonth( m, d ) Sets the month in local time or UTC, respectively. The second argument
representing the date is optional. If the optional argument is not specified, the
setUTCMonth( m, d ) current date value in the Date object is used.

setSeconds( s, ms ) Sets the second in local time or UTC, respectively. The second argument
representing the milliseconds is optional. If this argument is not specified, the109
setUTCSeconds( s, ms ) current millisecond value in the Date object is used.
METHODS OF THE DATE OBJECT…..
Me tho d De sc rip tio n

setTime( ms ) Sets the time based on its argument—the number of elapsed milliseconds
since January 1, 1970.
toLocaleString() Returns a string representation of the date and time in a form specific to the
computer’s locale. For example, September 13, 2001 at 3:42:22 PM is
represented as 09/13/01 15:47:22 in the United States and 13/09/01
15:47:22 in Europe.

toUTCString() Returns a string representation of the date and time in the form: 19 Sep 2001
15:47:22 UTC
toString() Returns a string representation of the date and time in a form specific to the
locale of the computer (Mon Sep 19 15:47:22 EDT 2001 in the United
States).
valueOf() The time in number of milliseconds since midnight, January 1, 1970.

110
THE DOCUMENT OBJECT MODEL
 Every web page resides inside a browser window can be considered as
an object.
 A Document object represents the HTML document that is displayed
in that window.
 The way that document content is accessed and modified is called
the Document Object Model, or DOM.
 The Objects are organized in a hierarchy which applies to the
organization of objects in a Web document.
 Window object: Top of the hierarchy. It is the outmost element of the
object hierarchy.
 Document object: Each HTML document that gets loaded into a
window becomes a document object.
 Form object: Everything enclosed in the <form>...</form> tags sets
the form object. 111
PART OF THE DOM
 window (browser window)
 Location (URL)
 document (HTML page)
 anchors <a>
 body <body>
 images <img>
 forms <form>
 elements <input>, <textarea>, <select>
 frames <frame>
 tables <table>
 Rows <tr>
cells <th>, <td>
 title <title> 112
JavaScript Object Hierarchy

113
• JavaScript define objects for all elements in a Web
page.
• Some widely used objects are:
• The Window object
• The Document object
• The History object
• The Location object
• The Navigator object

114
“WINDOW” OBJECT
 Basic idea:
 Primary task of a web browser is to display HTML
documents in a window.
 The “window” object represents the window (or
frame) where the document is being displayed.
 It is one of the highest-level objects in the JavaScript
object hierarchy.
 It represents the content area of the browser window
that can be divided into multiple frames or sub-
regions.
 Each sub region or frame is itself a window.

115
IMPORTANT PROPERTIES OF “WINDOW”:
 closed
 a Boolean value; true if window is closed.
 document
 represents the HTML document displayed in the

window.
 history
 represents the user’s browsing history.

 location

◦ represents the URL of the document displayed in the


window.
 name
116
◦ the name of the window.
 frames [ ]
◦ an array of window objects that represents the frames
within the window.
 parent

◦ if the current window is a frame, a reference to the frame


of the window that contains it.

117
IMPORTANT METHODS SUPPORTED BY
“WINDOW”:
 alert(),prompt(), confirm()
 displays dialog boxes (already discussed).

 close()
 close the window.

 open()
 opens a top-level window to display a specific URL

with a specified set of features.


 print()
 prints the window or frame.

118
 moveBy(), moveTo()
◦ moves the window to a new position.
 resizeBy(), resizeTo()

◦ changes the size of the window.


 scrollBy(), scrollTo()

◦ scrolls the document displayed in the window.


 setInterval(), clearInterval()

◦ schedules or cancels a function to be invoked repeatedly


with a specified delay.
 setTimeout(), clearTimeout()

◦ schedules or cancels a function to be invoked once after a


specified number of milliseconds.
119
“NAVIGATOR” OBJECT
• The Navigator Object is:
• The window.navigator object contains all information about
the visitor’s browser.
 Main properties:
 appName
 the simple name of the web browser.
 appVersion
 the version information for the browser.
 platform
 the hardware platform on which the browser is running.
 The properties of the “navigator” object are often more complex than
required.
E.g
var browser=navigator.appName; 120
var b_version=navigator.appVersion;
“SCREEN” OBJECT
 The window.screen object provides information about the
size of the user’s display & the number of color available
on it.
 Main properties:

◦ width, height
 size of the display in pixels.
◦ availWidth, availHeight
 display size that is actually available (excluding space required
by Windows taskbar, for example).

121
“LOCATION” OBJECT
 The window.location object represents the URL of the document
currently being displayed in the window.
 The Location Object is used to enable navigation to different URLs on
the Internet through JavaScript.
 Main properties:
 href
 contains a string that consists of the complete text of the URL.
 protocol, host, pathname, search
 contains the various individual parts of the URL.
 Methods supported by “location”:
 reload()
 reloads the currently displayed page from the web server.

 replace()
 loads a specified URL, and displays it.

 the specified URL replaces the current one in the browser’s history122

list.
“HISTORY” OBJECT
 The History Object contains a list of all pages that have
been visited in the browser window.
 The document.history object has been designed to model the
browsing history of a window as an array of recently
visited URLs.
 Elements of the array are not directly accessible, due to
security reasons.
 Only the “length” property of the “history” object can be
accessed which is an integer value representing the number
of links currently referenced by the History object .

123
 Property:

◦ length
 contains the number of URLs stored in the browsing

history.
 Methods:

◦ back()
 moves backward in the window’s browsing history.

◦ forward()
 moves forward in the window’s browsing history.

◦ go(x)
 takes an integer argument, and can skip forward or

backward in the history by the specified number of


pages.

124
“DOCUMENT” OBJECT

The Document Object is subordinate to the window


object in the document Object Model hierarchy.
The Document Object provides the properties and
methods to work with many aspects of the current
document, including information about anchors, forms,
links, title, current location and URL, and the current
colors.
The Document Object does not have any events
associated with it.

125
 The window.document object refers to the HTML document
displayed in the window.
 Main properties of “document” object:

◦ alinkColor, linkColor, vlinkColor


 specifies the color of hyperlinks (normal color of unvisited link,

normal color of visited link, and color of link while it is activated).


◦ anchors [ ]
 an array of “anchor” objects representing the anchors in the

document.
◦ applets [ ]
 an array of “applet” objects representing the Java applets in the

document.

126
 bgColor, fgColor
◦ represents the background and foreground colors of the
document.
 cookie
◦ a special property that allows Javascript programs to read and
write HTTP cookies.
 forms [ ]
◦ an array of “form” objects representing the <FORM>
elements in the document.
 images [ ]
◦ an array of “image” objects representing the <IMG> elements
in the document.

127
 lastModified
◦ last modification date of the document.
 links [ ]
◦ an array of “link” objects representing the hypertext links in
the document.
 location, URL
◦ specifies the URL from which the doccument was loaded.
 title
◦ the text between the <TITLE> and </TITLE> tags.

128
METHODS AVAILABLE IN “DOCUMENT”:
 open()
 opens a new document, overwriting any existing document
content.
 close()
 closes a document that was begun with open().

 write()
 appends text to the currently open document.

 writeln()
 outputs text to the currently open document, and append a

“newline” character,

129
JAVASCRIPT FORM OBJECT
 The JavaScript Form Object is a property of the document object.
 The Form object represents an HTML <form> element.
 A form can be submitted by calling the JavaScript submit method
or clicking the form submit button.
Form Object Properties
 action - This specifies the URL and CGI script file name the form is
to be submitted to.
 It allows reading or changing the ACTION attribute of the
HTML FORM tag.
 elements - An array of fields and elements in the form.

130
FORM OBJECT PROPERTIES
 method - This is a read or write string. It has the value "GET" or
"POST".
 name - The form name. Corresponds to the FORM Name attribute.
 target - The name of the frame or window the form submission
response is sent to by the server. Corresponds to the FORM
TARGET attribute
 encoding - This is a read or write string. It specifies the encoding
method the form data is encoded in before being submitted to the
server. It corresponds to the ENCTYPE attribute of the FORM tag.
The default is "application/x-www-form-urlencoded". Other
encoding includes text/plain or multipart/form-data.
 length - The number of fields in the elements array. I.E. the length of
the elements array.
131
FORM OBJECTS
Forms have their own objects.
 button - An GUI pushbutton control. Methods are click(), blur(), and
focus(). Attributes:
 name - The name of the button
 type - The object's type. In this case, "button".
 value - The string displayed on the button.
 checkbox - An GUI check box control. Methods are click(), blur(), and
focus(). Attributes:
 checked - Indicates whether the checkbox is checked. This is a read
or write value.
 defaultChecked - Indicates whether the checkbox is checked by
default. This is a read only value.
 name - The name of the checkbox.
 type - Type is "checkbox".
 value - A read or write string that specifies the value returned when132
the checkbox is selected.
 FileUpload - This is created with the INPUT type="file". This is the
same as the text element with the addition of a directory browser.
Methods are blur(), and focus(). Attributes:
 name - The name of the FileUpload object.
 type - Type is "file".
 value - The string entered which is returned when the form is
submitted.
 hidden - An object that represents a hidden form field and is used for
client/server communications. No methods exist for this object.
Attributes:
 name - The name of the Hidden object.
 type - Type is "hidden".
 value - A read or write string that is sent to the server when the
form is submitted.
133
 password - A text field used to send sensitive data to the server. Methods are
blur(), focus(), and select(). Attributes:
 defaultValue - The default value.
 name - The name of the password object."
 type - Type is "password".
 value - A read or write string that is sent to the server when the form is
submitted.
 radio - A GUI radio button control. Methods are click(), blur(), and focus().
Attributes:
 checked - Indicates whether the radio button is checked. This is a read or
write value.
 defaultChecked - Indicates whether the radio button is checked by
default. This is a read only value.
 length - The number of radio buttons in a group.
 name - The name of the radio button.
 type - Type is "radio".
 value - A read or write string that specifies the value returned when the 134
radio button is selected.
 reset - A button object used to reset a form back to default values.
Methods are click(), blur(), and focus(). Attributes:
 name - The name of the reset object.
 type - Type is "reset".
 value - The text that appears on the button. By default it is "reset".
 select - A GUI selection list. This is basically a drop down list. Methods
are blur(), and focus(). Attributes:
 length - The number of elements contained in the options array.
 name - The name of the selection list.
 options - An array each of which identifies an options that may be
selected in the list.
 selectedIndex - Specifies the current selected option within the select
list
 type - Type is "select".

135
 submit - A submit button object. Methods are click(), blur(), and
focus(). Attributes:
 name - The name of the submit button.
 type - Type is "submit".
 value - The text that will appear on the button.
 text - A GUI text field object. Methods are blur(), focus(), and
select(). Attributes:
 defaultValue - The text default value of the text field.
 name - The name of the text field.
 type - Type is "text".
 value - The text that is entered and appears in the text field. It is
sent to the server when the form is submitted.

136
 textarea - A GUI text area field object. Methods are blur(),
focus(), and select(). Attributes:
 defaultValue - The text default value of the text area field.
 name - The name of the text area.
 type - Type is textarea.
 value- The text that is entered and appears in the text area
field. It is sent to the server when the form is submitted
 Form Object Methods
 reset() - Used to reset the form elements to their default
values.
 submit() - Submits the form as though the submit button were
pressed by the user.
 Events
 onReset
 onSubmit 137
E N D
T H E
138

You might also like