Chapter 4 Javascript
Chapter 4 Javascript
different variables)
White space between words and tabs are ignored
Inline code
External file
I. External File
If you want to run the same JavaScript on several pages, you
var adult = confirm(“Are you sure you are older than 18 years?”)
if(adult)
alert(“Yes”);
else
3.Working with Variables and Data
followed by */
I. Arithmetic Operators
Arithmetic operators are used to perform arithmetic
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
= assignment operator
+= Add and then assign
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])
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
var someVal = 2;
someVal = someVal + 2;
someVal = someVal * 10;
someVal = someVal + “20”;
someVal = “Robert”;
5. Working with Conditional Statements
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
if (condition) {
statement(s) if true
}
[else if(condition){
statement(s) if true
}]
[else {
statement(s) if false
}]
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.
evaluates to false.
A do...while statement looks as follows:
do{
statement
}while (condition);
while Statement
A while statement executes its statements as long as a specified
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.
statement.
It is used to stop the loop when the condition we need is fulfilled.
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
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
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"]
];
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.
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.
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());
grade.reverse();
document.write("<br>Reversed: ");
for(var i=0;i<grade.length; i++)
document.write(" " + grade[i]);
Defining Functions
A function definition consists the function keyword, followed
by:
The name of the function.
braces { }.
Functions in JavaScript…
The syntax to define function:
function functionName ( [parameter1]...[,parameterN] ) {
statement[s]
}
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
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,
The value property of the input text box, is both readable and writable.
Event Handlers
onFocus - executed when input focus enters field (by tabbing in or by
of its text.
onChange - executed when input focus exits the field and the value of
name.
JavaScript will create an array using the name you've provided; you then
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,
NAME attribute.
selectedIndex - The index number of the currently selected
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
<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?