Programming
By Ray Yao
For Beginners
(With 100 Tests &
Answers)
Copyright © 2015 by Ray Yao
All Rights Reserved
Neither part of this book nor whole of
this book may be reproduced or
transmitted in any form or by any means
electronic, photographic or mechanical,
including photocopying, recording, or by
any information storage or retrieval
system, without prior written permission
from the author. All Right Reserved!
Ray Yao
Hour 2 Operators
Arithmetical Operators
Logical Operators
Assignment Operators
Comparison Operators
Conditional Operator
If Statement
If-else Statement
Switch Statement
For Loop
While Loop
Do-While Loop
Break Statement
Continue Statement
Hands-On Project: Number One
Hour 3 Array
Create an Array
Show array element values
Get the Size of Array
Join Array Elements
Reverse Element Order
Slice Elements
Sort Elements in Order
Change Elements to String
Search Specific Element (1)
Search Specific Element (2)
Add Element to Beginning
Remove First Element
Add Element to End
Remove Last Element
Hands-On Project: Reverse Order
Hour 5 String
String length
Join Strings
Search a Character
Convert Character Case
Change String to Array
Extract Substring
Convert a Number to String
Convert a String to a Number
Search Specific Text (1)
Search Specific Text (2)
Unicode
Add a Link for Text
Hands-On Project: UpperCase
Hour 6 Object
Object Declaration
Navigate Web Page
Go to Specified Page
Open Customized Window
Close Current Window
Confirmation
Prompt to Input
Address Element by ID
Get Elements by Tag Name
Connect two Strings
Convert Number to String
From Jan, 1, 1970
Absolute Value
Print Current Window
Check Java Enabled
Screen’s Width & Height
Hands-On Project: Max & Min
Hour 7 Event
HTML Basic
Click Event
Load Event
KeyPress Event
Mouseover Event
MouseOut Event
Keyup Event
Focus Event
Blur Event
Reset Event
Submit Event
Hands-On Project: Mouse Out
……
</Script>
Example 1.1
<html>
<head>
<title>Hello World</title>
</head>
<body>
<script language="javascript">
alert("Hello World!");
</script>
</body>
</html>
Output:
Hello World!
Explanation:
“<script type = “text/javascript”>” is a
tags for JavaScript. The JavaScript
codes are included within it.
“alert” pops up an alert box displaying a
message.
“alert (“Hello World!”)” displays
“Hello World!” message.
Each JavaScript command ends with
semicolon;
JavaScript block can locate anywhere in
HTML file.
Comment
Comment is used to explain the code.
// This is a single line comment
(Figure 1.2)
“document.write ("<h2>Hello World!
</h2>")” outputs “Hello World!”
If you want to edit the codes, right click
the file “FirstJavaScript.html” > open
with > Notepad.
Keywords
Keywords belong to JavaScript itself.
These may not be used when choosing
identifier names for variables, functions,
properties. The following are JavaScript
keywords:
break case continue defaul
delete do else export
false for function if
import in new null
return switch this true
typeof var void while
with Array Date Math
Object window location history
navigator document images links
forms elements getElementById innerH
Example 1.4
break // this is a JavaScript keyword.
return // this is a JavaScript keyword.
Explanation:
JavaScript keyword may not be used
when choosing identifier names for
variables, functions, properties.
Variables
Variable is a symbolic name associated
with a value. Variable uses “var” to
define.
Example 1.5
<script type = “text/javascript”>
var abcde; // abcde is a variable
var abc888; // abc888 is a variable
var my_variable; // my_variable is a
variable
</script>
Explanation:
abcde, abc888 and my_variable are all
variables.
They can store some value. e.g.
var abcde=100;
var abc888=”Hello World”;
var my_variable=true;
Notice that variable naming cannot start
with number, cannot have space. e.g.
“23var”, “abc de” are invalid variable
name.
But “var23”, “abcde” are valid variable
name.
Data Types
string – a character or a string of
characters
number – an integer or floating point
number
boolean – a value with true or false.
function – a user-defined method
object – a built-in or user-defined
object
Example 1.6
var mystring= “I am a string”;
var myinteger=168;
var myfloat=12.88;
var mybool=true;
Explanation:
var mystring=”I am a string”; // mystring
data type is string.
var myinteger=168; // myinteger data
type is number.
var myfloat=12.88; // myfloat data type
is number.
var mybool=true; // mybool data type is
boolean.
Note: Double quotes are always used in
string. e.g. “abcde”, “learning”.
Escape Sequences
The “ \ ” backslash character can be
used to escape characters.
\n outputs content to the next new line.
\r makes a return
\t makes a tab
\’ outputs a single quotation mark.
\” outputs a double quotation mark.
Example 1.7
<html>
<head>
<title>Escape</title>
</head>
<body>
<script language="javascript">
alert("JavaScript says \"Hello World!
\""); /* \” outputs a double quotation
mark. */
</script>
</body>
</html>
Output:
JavaScript says “Hello World!”
Explanation:
\” outputs a double quotation mark. Note
that “Hello World” has a double
quotation with it.
Another sample:
\t makes a tab
alert (“Hello \t\t\t World!”); // note it
has three taps
( Output: Hello World! )
Functions
A function is a code block that can
repeat to run many times. To define a
function, use “function function-name ( )
{ }”.
function function-name ( ) {……}
document.write( );
<html>
<head>
<title>Call a Function</title>
<head>
<body>
<script language="javascript">
function myFunction( ) // declare a
function
{
alert("Hello! A function has been
called!") // output
}
</script>
<form>
<br><br><br><br><br><br><br>
<center><input name="button"
type="button"
onclick="myFunction( )" value="Call
Function"><center>
</form> <!- - call the function - -
>
</body>
</html>
Operators
Arithmetical
Operators
Operators Running
+ add or connect s
- subtract
* multiply
/ divide
% get modulus
increase 1 or de
++ or --
1
% modulus operator divides the first
operand by the second operand, returns
the remainder. e.g. 4%2, remainder is 0.
Example 2.1
var add=100+200; alert (add); //
output 300
var div=800/2; alert ( div ); // output
400
var mod=10%3; alert ( mod ); //
output 1
var inc=10; alert ( ++inc ); // output
11
var str=”abc”+”de”; alert ( str ); //
output abcde
Explanation:
var add=100+200; alert ( add ) will
output 300
var div=800/2; alert ( div ) will output
400;
var mod=10%3; alert ( mod ) will
output 1;
var inc=10; alert ( ++inc ) will output
11;
var str=”abc”+”de”; alert ( str ) will
output abcde.
Logical Operators
Operators Equivalent
&& and
|| or
! not
After using logical operators, the result
will be true or false.
Example 2.2
var x=true; var y=false;
var a=x && y; alert ( a ); // output:
false
var b=x || y; alert ( b ); // output: true
var c=! x; alert ( c ); // output: false
Explanation:
true && true; true && false; false &&f
returns true; returns false; returns fal
true II true; true II false; false II fal
returns true; returns true; return fals
! false; ! true;
returns true; returns false;
Assignment Operators
Operators Examples: Equival
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
Example 2.3
var x=200; var y=100;
x+=y; alert ( x );
x/=y; alert ( x );
x-=y; alert ( x );
Operators Running
> greater than
< less than
greater than or
>=
equal
<= less than or equal
== equal
!= not equal
After using comparison operators, the
result will be true or false.
Example 2.4
var a=100; var b=200;
var result = (a>b); alert ( result );
var result = (a==b); alert ( result );
var result = (a!=b); alert ( result );
Explanation:
var result = (a>b); // test 100>200;
outputs false.
var result = (a==b); // test 100==200;
outputs false.
var result = (a!=b); // test 100!=200;
outputs true.
Conditional Operator
(test-expression) ? (if-true-do-this) :
(if-false-do-this);
if ( test-expression ) { // if true do
this; }
“if statement” executes codes inside {
… } only if a specified condition is true,
does not execute any codes inside {…}
if the condition is false.
Example 2.6
<html>
<head>
<title>
JavaScript Test
</title>
</head>
<body>
<script>
var a=200;
var b=100;
if (a>b) { // if true, do this
alert ( "a is greater than b" );
}
</script>
</body>
</html>
Output:
a is greater than b
Explanation:
( a>b ) is a test expression, namely
(200>100), if returns true, it will
execute the codes inside the { }, if
returns false, it will not execute the
codes inside the { }.
If-else Statement
Output:
Running case 20
Explanation:
The number value is 20; it will match
case 20, so it will run the code in case
20.
For Loop
Output:
012345
Explanation:
var x = 0 is an initializer, initializing
variable “x” as 0.
x <= 5 is test-expression, the code will
run at most 5 times.
x++ means that x will increase 1each
loop.
After 5 times loop, the code will output
012345.
While Loop
Output:
&&&&&&&&
Explanation:
“counter< 8” is a test expression, if the
condition is true, the code will loop less
than 8 times, until the counter is 8, then
the condition is false, the code will stop
running.
Do-While Loop
<html>
<head>
<title>
JavaScript Test
</title>
</head>
<body>
<script>
var counter=0;
do {
document.write ( "@" );
counter++;
} while (counter<8); // run 8 times
</script>
</body>
</html>
Output:
@@@@@@@@
Explanation:
“counter< 8” is a test expression, if the
condition is true, the code will loop less
than 8 times, until the counter is 8, then
the condition is false, the code will stop
running.
Break Statement
“break” command works inside the loop.
break;
“break” keyword is used to stop the
running of a loop according to the
condition.
Example 2.12
<html>
<head>
<title>
JavaScript Test
</title>
</head>
<body>
<script>
var num=0;
while (num<10){
if (num==5) break; // leave the while
loop
num++;
}
document.write( num );
</script>
</body>
</html>
Output:
5
Explanation:
“if (num==5) break;” is a break
statement. If num is 5, the program will
run the “break” command, the break
statement will leave the loop, then run
“document.write(num)”.
Continue Statement
“continue” command works inside the
loop.
continue;
“continue” keyword is used to stop the
current iteration, ignoring the following
codes, and then continue the next loop.
Example 2.13
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var num=0;
while (num<10){
num++;
if (num==5) continue; // go the next
while loop
document.write( num );
}
</script>
</body>
</html>
Output:
1234678910
Explanation:
Note that the output has no 5.
“if (num==5) continue;” means: When
the num is 5, the program will run
“continue” command, skipping the next
command “document.write( num )”, and
then continue the next while loop.
Hands-On Project:
Number One
For Loop Example
Open Notepad, write JavaScript codes:
<html>
<head>
<title>Number One</title>
</head>
<body>
<script language="javascript">
for(a=1;a<=6;a++){ // repeat 6 times
document.write( // output
"<h"+a+">"+"Number "+a+"
</h"+a+">");
}
</script>
</body>
</html>
Please save the file with name
“ForLoop.html”.
Note: make sure to use “.html”
extension name.
Double click “ForLoop.html” file, the
“ForLoop.html” will be run by a
browser, and see the output.
Output:
Explanation:
“for( init, test-expression, increment) {
// some code; }” runs a block of code
repeatedly by specified number of times.
a = 1 is an initializer, initializing
variable “a” as 1.
a <= 6 is test-expression, the code will
run at most 6 times.
a++ means that “a” will increase 1each
loop.
Hour 3
Array
Create an Array
An array is a particular variable, which
can contain one or more value at a time.
new Array( ) creates an array.
The syntax to create an array:
var array-name = new Array (“value0”,
“value2”);
Other syntax to create an array:
var array-name = new Array ( );
array-name[index0] = “value1”;
array-name[index1] = “value1”;
array-name[index2] = “value2”;
Example 3.1
var color = new Array ( ); // create an
array
color [0] = “red”;
color [1] = “blue”;
color [2] = “green”;
Explanation:
Above code creates an array, array name
is “color”, and it has three elements:
color [0], color [1], color [2]. Its
indexes are 0, 1, and 2. Its values are
red, blue, and green.
Note that index begins with zero.
Show array element
values
To show array element values, use
syntax as following:
document.write ( array-
name[index] );
Example 3.2
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
color = new Array("yellow", "purple",
"orange"); document.write ( color[1]
); // show array value
</script>
</body>
</html>
Output:
purple
Explanation:
From above, you can know:
The value of color[0] is yellow.
The value of color[1] is purple.
The value of color[2] is orange.
Note that the indexes begin counting
from zero.
Get the Size of Array
A function can get the size of an array.
array.length
Example 3.3
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var color = new Array("yellow",
"purple", "orange");
var size = color.length; // get the size
of an array
document.write ( size );
</script>
</body>
</html>
Output:
3
Explanation:
“var size=color.length” can return the
size of array “color”, and assigns the
size of array to “size”.
new Array(“yellow”, “purple”,
“orange”) has three elements, so its size
is 3.
Join Array Elements
array.join( );
array.join(“ ”);
array.join(“ , ”);
array.join( ); can join all array
elements without spaces.
array.join(“ “) can join all array
elements by spaces.
array.join(“,”) can join all array
elements by commas.
Example 3.4
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var arr = new Array( );
arr[0] = "I";
arr[1] = "Love";
arr[2] = "JavaScript!";
document.write( arr.join(" ") ); // join
elements by spaces
</script>
</body>
</html>
Output:
I Love JavaScript!
Explanation:
arr.join(“ ”) can join all elements of the
“arr” together by spaces. Of course you
can try arr.join(“,”) to join elements by
commas.
Reverse Element
Order
array.reverse( );
“array.reverse( )” can reverse the
element order of an array.
Example 3.5
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var arr = new Array( "A", "B", "C" );
arr.reverse( ); // reverse the elements
order
var rev = arr.join(","); // join all
elements by “,”
document.write( rev );
</script>
</body>
</html>
Output:
C, B, A
Explanation:
“arr.reverse( )” reverses the element
order of “arr” array.
“rev=arr.join(“,”)” joins all elements of
“arr” array together and assign the value
with new element order to “rev”.
Slice Elements
array.sort( )
“array.sort( )” can sort array elements
orderly.
Example 3.7
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var arr = new Array( 2, 5, 3, 1, 4, 6 );
arr.sort ( ); // sort all elements in order
var sor = arr.join(","); // join all
elements by “,”
document.write( sor );
</script>
</body>
</html>
Output:
1,2,3,4,5,6
Explanation:
“arr.sort ( )” sort the elements of “arr”
sequentially.
“var sor = arr.join(“,”)” joins the
elements of “arr” by commas; and assign
the value to “sor”.
Change Elements to
String
array.toString();
“array.toString()” can change the
elements of an array to string.
Example 3.8
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var myarray = new Array( );
myarray[0] ="Mon";
myarray[1] ="Tue";
myarray[2] ="Wed";
var threedays = myarray.toString( ); //
conver to string
document.write( threedays );
</script>
</body>
</html>
Output:
Mon, Tue, Wed
Explanation:
“myarray.toString( )” converts all
elements in myarray to a string whose
value is “Mon, Tue, Wed”.
Search Specific
Element (1)
indexOf( )
“indexOf( )” can find the first place
where a particular element occurs in an
array.
Example 3.9
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var myarray = new Array( );
myarray[0] ="Mon";
myarray[1] ="Tue";
myarray[2] ="Wed";
myarray[3] ="Tue";
var num = myarray.indexOf ("Tue");
// get index of “Tue”
alert(num);
</script>
</body>
</html>
Output:
1
Explanation:
“myarray.indexOf ( “Tue” )” returns the
first place where the “Tue” occurs in
myarray. The output is 1.
If the element is not found in array,
indexOf( ) returns -1.
Search Specific
Element (2)
lastIndexOf( )
“lastIndexOf( )” can find the last place
where a particular element occurs in an
array.
Example 3.10
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var myarray = new Array( );
myarray[0] ="Mon";
myarray[1] ="Tue";
myarray[2] ="Wed";
myarray[3] ="Tue";
var num=myarray.lastIndexOf ( "Tue"
); // get index of “Tue”
alert(num);
</script>
</body>
</html>
Output:
3
Explanation:
“myarray.lastIndexOf ( “Tue” )” returns
the last place where the “Tue” occurs in
myarray. The output is 3.
If the element is not found in array,
lastIndexOf( ) returns -1.
Add Element to
Beginning
unshift( )
Add one or more elements into the
beginning of an array.
Example 3.11
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var arr = [4,5,6];
arr.unshift(1,2,3); //add 1,2,3 to the
beginning of “arr”
alert(arr);
</script>
</body>
</html>
Output:
1,2,3,4,5,6
Explanation:
unshift() adds one or more elements into
the beginning of an array.
“arr.unshift(1,2,3);” adds elements 1,2,3
to the beginning of “arr”.
Remove First Element
shift( )
Remove the first element of an array.
Example 3.12
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var arr = [4,5,6];
arr.shift( ); //remove the first element
of the array
alert(arr);
</script>
</body>
</html>
Output:
5, 6
Explanation:
shift() removes the first element of an
array.
“arr.shift( );” removes the first element
of the array “arr”.
Add Element to End
push( )
Add one or more elements to the end of
an array.
Example 3.13
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var arr = [1,2,3];
arr.push(4,5,6); //add 4,5,6 to the end
of “arr”
alert(arr);
</script>
</body>
</html>
Output:
1,2,3,4,5,6
Explanation:
push() adds one or more elements to the
end of an array.
“arr.push(4,5,6);” adds 4,5,6 to the end
of “arr”.
Remove Last Element
pop( )
Remove the last element of an array.
Example 3.14
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var arr = [1,2,3,4,5,6];
arr.pop( ); //remove the last element of
arr
alert(arr);
</script>
</body>
</html>
Output:
1,2,3,4,5
Explanation:
pop() removes the last element of an
array.
“arr.pop( );” removes the last element of
arr.
Hands-On Project:
Reverse Order
Array Example:
Open Notepad, write JavaScript codes:
<html>
<head>
<script>
var oldArray = new Array(0,1,2,3,4,5);
document.write(
"Original array is: "+oldArray.join()+"
<br>");
var newArray=oldArray.reverse();
//reverse elements order
document.write(
"Reversed array is:
"+newArray.join()+"<br>");
</script>
</head>
</html>
Output:
Original array is: 0,1,2,3,4,5
Reversed array is: 5,4,3,2,1,0
Explanation:
“array.join()” connects all array
elements together.
“array.reverse()” reverses the order of
all array elements
Hour 4
Math, Time
Math Methods
Method Returns
abs( ) a number’s absolute value
an integer greater than or
ceil( )
equal its argument
an angle’s trigonometric
cos( )
cosine
a number’s Math.E to the
exp( )
power
an integer less than or equal
floor( )
its argument.
a number’s natural
log( )
logarithm
random( a random positive value
) from 0 to 1
a greater between two
max( )
numbers
a smaller between two
min( )
numbers
the first argument to the
pow( )
power of the second
round( ) an integer
an angle’s trigonometric
sin( )
sine
sqrt( ) a number’s square root
an angle’s trigonometric
tan( )
tangent
Example 4.1
var num = 10.2;
document.write ( Math.round(num) );
// Output: 10
Explanation:
Math.round(num) returns an integer of
10.2. Result is 10.
Greater & Less
Math.ceil( );
Math.floor( );
“Math.ceil( );” returns a closest integer
that is greater than or equal to its
argument.
“Math.floor( );” returns a closest integer
that is less than or equal to its argument.
Example 4.2
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var num = 9.5;
document.write ("Ceiling number is
"+Math.ceil( num )+"<br>" );
document.write ("Flooring number is
"+Math.floor( num )+"<br>" );
</script>
</body>
</html>
Output:
Ceiling number is 10
Flooring number is 9
Explanation:
“Math.ceil( num ));” returns a closest
integer that is greater than or equal 9.5,
the result is 10
“Math.floor( num );” returns a closest
integer that is less than or equal 9.5, the
result is 9
Maximum &
Minimum
Math.max( );
Math.min( );
“Math.max( )” returns the greater one
between two numbers.
“Math.min( )” returns the less one
between two numbers.
Example 4.3
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var x = 100;
var y = 200;
document.write ("Greater number
is"+Math.max(x, y)+"<br>" );
document.write ("Less number
is"+Math.min(x, y)+"<br>");
</script>
</body>
</html>
Output:
Greater number is 200
Less number is 100
Explanation:
“Math.max(x, y)” returns the greater
number between 100 and 200, the result
is 200.
“Math.min(x, y)” returns the less number
between 100 and 200, the result is 100.
Power Value
pow( ) returns the value of x to the
power of y.(xy)
Example 4.4
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var num1 = Math.pow(6, 2);
alert( num1);
var num2 = Math.pow(2, 3);
alert( num2 );
</script>
</body>
</html>
Output:
36
8
Explanation:
Math.pow(6,2) equals 62.
Math.pow(2,3) equals 23.
Square Root
sqrt( ) returns the square root of a
number.
Example 4.5
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var num1 = Math.sqrt(4);
alert( num1 );
var num2 = Math.sqrt(25);
alert( num2 );
</script>
</body>
</html>
Output:
2
5
Explanation:
Math.sqrt(4) returns the square root of
the number 4.
Math.sqrt(25) returns the square root of
the number 25.
PI & Random Value
Math.PI
Math.random( )
Math.PI is a constant that stores the
value of pi.
Math.random( ) generates a number
between 0.0 to 1.0.
Example 4.6
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var pi = Math.PI;
var ran = Math.random( );
document.write ("The PI value is " + pi
+ "<br>");
document.write ("The random number is
" + ran);
</script>
</body>
</html>
Output:
The PI value is 3.141592653589793
The random number is
0.6315033452119678
Explanation:
The value of Math.PI is
3.141592653589793.
Math.random( ) generates a random
number between 0.0 to 1.0, in here the
result is 0.6315033452119678
Date & Time
JavaScript often use date and time to
design the web page. When using date
and time, you must create an object of
date first.
var DateObject = new Date( )
“new Date( )” can create an object of
date.
Example 4.7
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var DateObject = new Date( ); //
create a date object
alert ( DateObject );
</script>
</body>
</html>
Output:
Thu Nov 05 2015 21:39:28 GMT-0500
(Eastern Standard Time)
Explanation:
“var DateObject = new Date( )” creates
an object of date.
“alert ( DateObject )” displays the
current date and time.
Note that: To create a date object, you
can use other variable name, for
instance:
var now= new Date( );
var TimeObjcet = new Date( );
Date, Month, Year,
Day
The Date Object has following method:
getDate( ) get the date
getMonth( ) get the month
getYear( ) get the year
getDay( ) get the day
getFullYear() get the full year
Note:
“getDay( )” returns from 0 (Sunday) to 6
(Saturday).
“getMonth( )” returns from 0 (January)
to 11 (December).
“getYear( )” returns a year , but need to
add 1900.
“getFullYear()” returns a year with
correct format.
Example 4.8
<html>
<body>
<script>
var now = new Date ( ); // create a date
object
var m = now.getMonth( ) + 1; // note it
need add 1
var d = now.getDate( );
var y = now.getYear( ) + 1900; // note it
need add 1900
var fy = now.getFullYear();
alert ( m + " - " + d + " - " + y + "\n\n"
+ "This year is " + fy);
</script>
</body>
</html>
Output:
11- 6 - 2015
This year is 2015
Explanation:
“now.getMonth( )” returns a month, but
need to add 1.
“now.getDate( )” returns a current date.
“now.getYear( )” returns a year, but need
to add 1900.
“getFullYear()” returns a year with
correct format.
Hours, Minutes,
Seconds
The Date Object has following method:
getHours( ) get the hours
getMinutes( ) get the minutes
getSeconds( ) get the seconds
getTime( ) get the time
Note that getTime( ) returns a number
from January 1,1970 to current time.
Example 4.9
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var now = new Date( ); // create a date
object
var h = now.getHours( );
var m = now.getMinutes( );
var s = now.getSeconds( );
alert ( "Current time is " + h + ":" + m +
":" + s );
</script>
</body>
</html>
Output:
Current time is 19:30:28
Explanation:
“getHours” returns the current hours.
“getMinutes” returns the current minutes.
“getSeconds” returns the current
seconds.
Different Time
getUTCHours( )
getTimezoneOffset( )
“getUTCHours( )” returns the
Greenwich Mean Time. (UTC)
“getTimezoneOffset( )” returns the time
difference between UTC time and local
time. For example, if your time zone is
GMT+2, -120 will be returned.
Example 4.10
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var now = new Date( ); // create a date
object
var utc = now.getUTCHours( ); //get
Greenwich Mean Time
var timezone =
now.getTimezoneOffset( ); //get time
zone
alert ( utc )
alert ( timezone );
</script>
</body>
</html>
Output:
13
300
Explanation:
“getUTCHours( )” returns the UTC hour.
“getTimezoneOffeset” returns a number.
For instance,
300 means Eastern Time. 360 means
Central Time. 420 means Mountain
Time. 480 means Pacific Time.
Set Date & Time
The Date Object has following method:
setFullYear( ) set the year
setMonth( ) set the month
setDate( ) set the date
setHours( ) set the hours
setMinutes( ) set the minutes
setSeconds( ) set the seconds
Note: Please use setFullYear( ) instead
of setYear( ).
Example 4.11
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var now = new Date(); // crearte a date
object
now.setMonth(0);
now.setDate(18);
now.setFullYear(2016);
var today = now;
document.write(today);
</script>
</body>
</html>
Output:
Mon Jan 18 2016 09:38:41 GMT-0500
(Eastern Standard Time)
Explanation:
“setMonth(0), setDate(18) and
setFullYear(2016) set the month, date
and year as Jan 18 2016.
“0” represents January in setMonth(0).
Timer Function
window.setTimeout( )
“window.setTimeout( )” can set interval
time to perform an action repeatedly.
Example 4.12
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body onload="autoTimer()">
<script>
var count=0;
function autoTimer( ) // user-defined
function
{
count++;
document.write( count ); // show the
increasing numbers
window.setTimeout( "autoTimer()" ,
5000 ); /* call autoTime() every other
5 seconds */
}
</script>
</body>
</html>
Output:
12345678……
Explanation:
“window.setTimeout( )” can set interval
time to perform an action repeatedly.
“autoTimer( );” calls the function
“autotimer( ){ }” every other 5000
milliseconds, which is a user-defined
function.
“5000” represents 5000 milliseconds,
which sets every 5000 milliseconds for
autoTimer( ) to call function.
The increasing number displays every
other 5 seconds.
Hands-On Project:
This Month…
Show Current Month
Open Notepad, write JavaScript codes:
<html>
<head>
<script>
var dateObj=new Date(); // create a
date object
document.write(
"The current month is: "+
(dateObj.getMonth()+1));
</script>
</head>
</html>
// Note: the index of month starts with 0.
// “0” represents January. “1” represents
February……
Please save the file with name
“ShowMonth.html”.
Note: make sure to use “.html”
extension name.
Double click “ShowMonth.html” file,
the “ShowMonth.html” will be run by a
browser, and see the output.
Output:
The current month is: 11
Explanation:
“var dateObj=new Date();” creates a
Date Object.
Date Object has many methods that is
used to set or get the date information.
“getMonth( )” returns a number from 0
(January) to 11 (December).
Hour 5
String
String length
string. length
“string.length” can calculate the string
length, including spaces.
Example 5.1
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var mystring = "I love JavaScript";
var stringsize = mystring.length; // get
the string length
document.write( "String length is " +
stringsize );
</script>
</body>
</html>
Output:
String length is 17
Explanation:
“mystring.length” returns the length of
mystring, including spaces.
Join Strings
string.toUpperCase( )
string.toLowerCase( )
“toUpperCase( )” and “toLowerCase( )”
can change word’s case.
Example 5.4
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var mystring = "Hello World!";
var big = mystring.toUpperCase( );
var small = mystring.toLowerCase( );
document.write( "Uppercase is " + big +
"<br>" );
document.write( "Lowercase is " +
small);
</script>
</body>
</html>
Output:
Uppercase is HELLO WORLD!
Lowercase is hello world!
Explanation:
“mystring.toUpperCase( )” and
“str.toLowerCase( )” change the case of
mystring.
“<br>” changes to new line.
Change String to
Array
string.split( “ ” );
“string.split(“ ”);” can change a string to
an array.
Argument (“ ”) is a separator which
separates the string to elements of the
array by space.
Example 5.5
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var mystring = "JavaScript for
Beginners";
var myarray = mystring.split( " " ); /*
convert a string to an array, separate all
elements by spaces */
document.write( "<br>" + myarray[0]);
document.write( "<br>" + myarray[1]);
document.write( "<br>" + myarray[2]);
</script>
</body>
</html>
Output:
JavaScript
for
Beginners
Explanation:
“mystring.split( “ ” )” separates the
string to elements by space separator,
which makes three elements:
myarray[0], myarray[1], myarray[2].
Extract Substring
number.toString( );
To meet the requirement of JS
programming, sometimes a number
needs to convert to a string data type.
“number.toString( )” can change a
number to a string.
Example 5.7
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var num1 = 12; var num2 = 68;
var str1 = num1.toString( );
var str2 = num2.toString( );
var sum = str1 + str2; // connecting
instead of adding
document.write( sum );
</script>
</body>
</html>
Output:
1268
Explanation:
“num1.toString( )” and “num2.toString(
)” change two numbers to string data
type. Therefore, the result of str1 adding
str2 is 1268, instead of 80.
Convert a String to a
Number
parseInt(string);
parseFloat( string);
“parseInt(string)” and parseFloat(string)
can change a string to integer or floating
point number.
Example 5.8
var str1 = “12”; var str2 = “68”;
var sum = str1 + str2;
alert ( sum );
( Output: 1268 )
var num1 = parseInt( str1 );
var num2 = parseInt( str2 );
var addition = num1 + num2; // add
instead of join
alert ( addition );
( Output: 80 )
Explanation:
“parseInt( str1)” and “parseInt( str2 )”
convert two strings to number data type.
Therefore, the result of num1adding
num2 is 80, instead of 1268.
Search Specific Text
(1)
indexOf( )
“indexOf( )” can find the first place
where a particular text occurs in a string.
Example 5.9
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var mystring = "Please find where find
word occurs!";
var place = mystring.indexOf("find");
// return index
alert ( place );
</script>
</body>
</html>
Output:
7
Explanation:
“mystring.indexOf ( “find” )” returns the
first place where the “find” occurs in
mystring. The output is 7.
Character index begins with zero.
If the text is not found in string, indexOf(
) returns -1.
Search Specific Text
(2)
lastIndexOf( )
“lastIndexOf( )” can find the last place
where a particular text occurs in a string.
Example 5.10
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var mystring = "Please find where find
word occurs!";
var place =
mystring.lastIndexOf("find"); //
return index
alert ( place );
</script>
</body>
</html>
Output:
18
Explanation:
“mystring.lastIndexOf ( “find” )” returns
the last place where the “find” occurs in
mystring. The output is 18.
Character index begins with zero.
If the text is not found in string, indexOf(
) returns -1.
Unicode
strObject.charCodeAt(index)
“strObject.charCodeAt(index)” returns
Unicode code at specified position.
Example 5.11
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var myString = "Hello world!";
var result = myString.charCodeAt(4);
// return unicode
alert("The Unicode of the 5th character
is " + result );
</script>
</body>
</html>
Output:
The Unicode of the 5th character is 111.
Explanation:
“charCodeAt(4)” returns the Unicode at
the 5th character.
Note: Index starts with 0.
The 5th character is “o”, its Unicode is
111.
Add a Link for Text
strObject.link(linkString)
“strObject.link(linkString)” adds a link
for a string.
Example 5.12
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var myString = "Please click me!";
var result =
myString.link("http://www.xxxxxx.xxx"
// add a hyperlink for the string
document.write("Welcome to our
website: " + result );
</script>
</body>
</html>
Output:
Welcome to our website: Please click
me!
Explanation:
“myString.link(“http://www.xxxxxx.xxx”)”
adds a link of “www.xxxxxx.xxx” to
myString.
When you click “Please click me!”; it
redirects to specified website.
Hands-On Project:
UpperCase
String Operation
Open Notepad, write JavaScript codes:
<html>
<head>
<script>
var oldText="Java in 8 Hours"
var newText= oldText.toUpperCase();
document.write("Original: Java in 8
Hours<br>");
document.write("Uppercase: "+
newText);
</script>
</head>
</html>
Please save the file with name
“ToUppercase.html”.
Note: make sure to use “.html”
extension name.
Double click “ToUppercase.html” file,
the “ToUppercase.html” will be run by a
browser, and see the output.
Output:
Original: Java in Hours
Uppercase: JAVA IN 8 HOURS
Explanation:
“string.toUpperCase()” changes the
string letters to upper case.
“string.toLowerCase()” changes the
string letters to lower case.
Hour 6
Object
Object Declaration
Object refers to a concrete something.
For example: a car, a book, a dog, a
house, etc…
obj = new Object( );
obj.property;
“obj = new Object( )” creates a new
object named “obj”.
“obj.property” means a object’s
property.
Example 6.1
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
house = new Object ( ); // create an
object “house”
house.color = "white"; // an object
references a variable
house.size = "big"; // an object
references a variable
document.write( "House color: " +
house.color + "<br>");
document.write( "House size: " +
house.size + "<br>" );
</script>
</body>
</html>
Output:
House color: white
House size: big
Explanation:
“house=new Object( )” creates an object
name “house”.
“house.color” means house’s color.
“house.size” means house’s size.
Navigate Web Page
windows.history.back( );
windows.history.forward( );
“back( )” is used to navigate the
previous web page.
“forward( )” is used to navigate the next
web page.
Example 6.2
windows.history.back( ); // to last
page
( Returns: Previous web page. )
windows.history.forward( ); // to next
page
( Returns: Next web page. )
Explanation:
“back( )” goes to previous page.
“forward( )” goes to next page.
“window.history.method( )” is used to
navigate the specified web page. This
method is usually called by a button on
web page, which will be mentioned in
later chapter.
Go to Specified Page
window.history.go( number );
“window.history.go( number)” can turn
to specified web page.
Example 6.3
window.history.go(1); // to next page
( Returns: Next web page.)
window.history.go( 0 );
( Returns: Reload current web page.)
Explanation:
“window.history.method( )” is used to
navigate the specified web page. This
method is usually called by a button on
web page, which will be mentioned in
later chapter.
Open Customized
Window
Output:
This is a new window.
Explanation:
“MyWindow” is a new window name.
“height=200,width=350” specify the size
of new window.
“toolbar=yes” means there is a toolbar.
“memubar=yes” means there is a menu
bar.
“status= no” means there is no status
bar.
“top=200,left=200” specifies the
location of the new window.
Close Current
Window
window.close( );
“window.close( );” can close the current
window.
For example:
<html>
<script>
function closeWindow(){
window.close( ); // close the current
window
}
</script>
<form>
<center><br><br>
<input type = "button"
onclick = "closeWindow()" // click and
call the function
value = "Close Window">
</center>
</form>
</html>
Explanation:
“window.close( )” is used to close the
current window.
Confirmation
window.confirm( );
“window.confirm( )” requires user to
confirm. Confirm dialog box looks like
this:
document.getElementById( ).innerHTML
document.getElementsByTagName( ).inn
“getElementsByTagName” access
elements by their tag name.
“innerHTML” displays or get value in
HTML document.
Example 6.8
<html>
<body>
<ol>
<li>Red</li>
<li>Yellow</li>
<li>Green</li>
</ol>
<button
onclick="myFunction()">Click</button>
<p id="show"></p>
<script>
function myFunction() {
var col =
document.getElementsByTagName("li"
// get all values by tag “li”, such as Red,
Yellow, Green
document.getElementById("show").innerH
= col[2].innerHTML; /* display the
third element to id “show”, col[2] means
the third element “Green”. */
}
</script>
</body>
</html>
Output:
Green
Explanation:
“getElemenstByTagName(“li”)” access
“li” tag and get their values.
“document.getElementById("show").inner
shows value of the element in tag
“show”.
“col[2].innerHTML;” means the value of
the col[2], the third element’s value.
Connect two Strings
string1.concat(string2);
Number.toFixed(decimalPlace);
“Number.toFixed(decimalPlace);”
converts a number into a string with
specified decimal place.
Example 6.10
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var num = 10.28;
var str = num.toFixed(1); // 1 is
decimal place
document.write(str);
</script>
</body>
</html>
Output:
10.3
Explanation:
Number.toFixed( decimalPlace)
converts a number into a string with
specified decimals place.
“var str = num.toFixed(1);” converts the
decimal number to string with 1 decimal
place.
From Jan, 1, 1970
Date.parse(dateValue);
Output:
(Display the “Print Window”)
Explanation:
window.print( ) prints the contents of
current window.
onclick=”printWindow( ) calls the
function “printWinow( )” when clicking
the button.
Check Java Enabled
navigator.javaEnabled( ) checks the
browser whether it supports Java.
Example 6.14
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
if(navigator.javaEnabled( ) == true)
/* checks the browser whether it
supports Java. */
document.write("The browser supports
the Java.");
else
document.write("The browser doesn’t
support the Java.");
</script>
</body>
</html>
Output:
The browser supports the Java.
Or:
The browser doesn’t support the Java.
Explanation:
navigator.javaEnabled( ) checks the
browser whether it supports Java.
Screen’s Width &
Height
Screen.width returns the width of screen.
Screen.height returns the height of
screen.
Example 6.15
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body>
<script>
var w = screen.width;
document.write(w + "<br>");
var h = screen.height;
document.write(h + "<br>");
</script>
</body>
</html>
Output:
1024
768
Explanation:
Screen.width returns the width of screen.
Screen.height returns the height of
screen.
Hands-On Project:
Max & Min
Math Object
Open Notepad, write JavaScript codes:
<html>
<head>
<script>
var number1 = 20;
var number2 = 50;
var number3 = 80;
document.write(
"The maximum number among 20, 50, 80
is: "+
Math.max(number1,number2,number3)+"
<br><br>");
// return maximum among three numbers
document.write(
"The minimum number among 20, 50, 80
is: "+
Math.min(number1,number2,number3)+"
<br><br>");
// return minimum among three numbers
</script>
</head>
</html>
Output:
The maximum number among 20, 50, 80 is: 80
The minimum number among 20, 50, 80 is: 20
Explanation:
“Math.max( )” gets the maximum
number.
“Math.min( )” gets the minimum number.
Hour 7
Event
HTML Basic
When we check the source code of a
web page, we will find some HTML
elements or tags, which look like this:
Example 7.1
<html>
<head>
<title>…</title>
</head>
<body>
<form>…</form>
…..
</body>
</html>
Explanation:
<html>…</html> define the document
of a web page.
<head>…</head> define the head of a
web page.
<title>…</title> define the title of a
web page.
<body>…</body> define the body of a
web page.
<form>…</form> define a form, which
accepts the requests or input from a user.
Click Event
When a user clicks an element on the
web page, a “click” event occurs.
onClick = function( );
“onClick = function( );” means when
clicking an element, a function
immediately executes.
Example 7.2
<form>
<input type=“button” value=”Previous”
onClick=“history.back( )”> <!- -
click event - ->
</form> ( Returns: Previous web
page. )
Explanation:
“<from>” and “</form>” is HTML tags,
which is in web page, “form” is used to
accept the request from users.
“<input type=“button”
value=”Previous”…>” defines a button
in the form, the button has “Previous”
text on it.
“onClick=“history.back( )”” means
when clicking the button, the
“history.back( )” runs at once, and then
go back to Previous web page.
Load Event
When a web page has completely
loaded, an “Load” event occurs.
onload = “function( )”
onload=”function( )” executes the
function when a web page has loaded.
Example 7.3
<html>
<head>
<title>
JavaScript Codes
</title>
</head>
<body onload = "test( )"> <!- - load
event - ->
<script>
function test(){
alert ("Welcome to my website!");
}
</script>
</body>
</html>
Output:
Welcome to my website!
Explanation:
<html> and </html> is html tags, which
defines a web page.
<body> and </body> define a web page
body.
onload= “test( )” executes test()
immediately when web page has been
loaded.
KeyPress Event
When a key is pressed, an “KeyPress”
event occurs.
onKeyPress = function( );
“onKeyPress=function( )” executes the
function when a key is pressed.
Example 7.4
<html>
<head>
<title>JavaScript Codes</title>
<script type="text/JavaScript">
function myFunction(msg) {
alert(msg);
}
</script>
</head> <!- - keypress event - ->
<body
onkeypress="myFunction('Hello! My
Friend.')">
Please press a key.
</body>
</html>
Output:
Hello! My Friend.
Explanation:
<html> and </html> is html tags, which
defines a web page.
<body> and </body> define a web page
body.
“onKeyPress=function( )” executes the
function when a key is pressed.
Mouseover Event
When a mouse pointer moves over an
element, a “mouseover” event occurs.
onMouseOver = function( );
“onMouseOver = function( )” executes
the function immediately when mouse
moves over an element.
Example 7.5
<html>
<head>
<title>
JavaScript Codes
</title>
<script type="text/JavaScript">
function myFunction(msg) {
alert(msg);
}
</script>
</head>
<body>
<br>
<center> <!- - mouseover event - ->
<textarea
onMouseOver="myFunction('MouseOv
event occurs!')"> Please put the mouse
on me!</textarea>
</center>
</body>
</html>
Output:
MouseOver event occurs!
Explanation:
“onMouseOver="myFunction();”
executes myFunction() immediately
when the mouse moves over an element.
MouseOut Event
When a mouse pointer moves out of an
element, a “mouseout” event occurs.
onMouseOut = function( );
“onMouseout = function( )” means when
mouse pointer moves out of an element,
function( ) executes immediately.
Example 7.6
<html>
<head>
<title>
JavaScript Codes
</title>
<script type="text/JavaScript">
function myFunction(msg) {
alert(msg);
}
</script>
</head>
<body>
<br>
<center> <!- - mouseout event - ->
<textarea
onMouseOut="myFunction('See
You!')"> Please move the mouse away.
</textarea>
</center>
</body>
</html>
Output:
See You!
Explanation:
“onMouseout=myFunction( );” executes
myFunction() when mouse leaves the
textarea.
Keyup Event
When a key is released, a “Keyup” event
occurs.
onkeyup = function( );
“onkeyup = function( )” means when a
key is released, a function( ) executes
immediately.
Example 7.7
<html>
<head>
<title>Untitled Document</title>
<script type="text/JavaScript">
function myFunction(msg) {
alert(msg);
}
</script>
</head> <!- - keyup event - ->
<body onkeyup="myFunction('Keyup
event occurs!')">
Please press a key, and release.
</body>
</html>
Output:
Keyup event occurs!
Explanation:
“onkeyup="myfunction( )"” means when
a key is released, myfunction( ) runs at
once.
Focus Event
When the user moves the cursor onto an
element in the web page, a “focus” event
occurs.
onfocus = function ( );
“onfocus = function ( )” means when the
user moves the cursor onto an element of
the web page, a function( ) immediately
executes.
Example 7.8
<html>
<head>
<title>JavaScript Codes</title>
</head>
<body>
<script>
function myfunction( )
{ confirm ("Are you ready to input
data?");}
</script>
<center> <!- - focus event - ->
<input type="text"
onfocus="myfunction( )">
</center>
</body>
</html>
Output:
Are you ready to input data?
Explanation:
“onfocus="myfunction( )"” means when
the user moves the cursor onto input
field in the web page, myfunction( )
immediately executes.
Blur Event
When the user moves the cursor out of an
element in the web page, a “blur” event
occurs.
onblur = function ( );
“onblur = function ( )” means when the
user moves the cursor out of an element
of the web page, a function( )
immediately executes.
Example 7.9
<html>
<head>
<title>JavaScript Codes</title>
</head>
<body>
<script>
function myfunction( )
{ confirm ("Are you sure to leave?");}
</script>
<center> <!- - blur event - ->
<input type="text"
onBlur="myfunction( )">
</center>
</body>
</html>
Output:
Are you sure to leave?
Explanation:
“onblur="myfunction( )"” means when
the user moves the cursor out of input
field in the web page, myfunction( )
immediately executes.
Reset Event
onreset = “ScriptCode( )”
onreset = “ScriptCode( )” executes the
“ScriptCode( )” when the form is reset.
Example 7.10
<html>
<head>
<title>JavaScript Codes</title>
</head>
<body>
<br>
<br>
<br>
<center> <!- - reset event - ->
<form onreset = "alert('The form has
been reset!')">
<input type = "text" id = "txt">
<input type = "reset" value = "RESET"
>
</form>
</center>
</body>
</html>
Output:
The form has been reset!
Explanation:
onreset = “alert(‘The form has been
reset!’)” runs alert( ) when clicking the
RESET button.
Submit Event
onsubmit = “ScriptCode( )”
onsubmit = “ScriptCode( )” executes the
“ScriptCode( )” when the form is
submitted.
Example 7.11
<html>
<head>
<title>JavaScript Codes</title>
</head>
<body>
<br>
<br>
<br>
<center> <!- - submit event - ->
<form onsubmit = "alert('The form
has been submitted!')">
<input type = "text" id = "txt">
<input type = "submit" value = "submit"
>
</form>
</center>
</body>
</html>
Output:
The form has been submitted!
Explanation:
onsubmit = “alert(‘The form has been
submitted!’)” runs alert( ) when clicking
the SUBMIT button.
Hands-On Project:
Mouse Out
Event Example
Open Notepad, write JavaScript codes:
<html>
<head>
<script>
function show1(){
var
y=document.getElementById("textID");
y.value ="Welcome!";
}
function show2(){
var
y=document.getElementById("textID");
y.value ="Good Bye!";
}
</script>
</head>
<body><br><br>
<center> <!- - mouseover &
mouseout event - ->
<input type="text" id="textID"
onMouseOver=" show1()"
onMouseOut=" show2()"/>
</center>
</body>
</html>
Output:
Explanation:
“onMouseOver=" show1()"” executes
function show1() when mouse moves
over the text field.
“onMouseOut=" show2()” executes
function show2() when mouse moves out
the text field.
Hour 8
Form & Dom
Form Basic
A “form” in html is a very important
element, which is used to accept the
requests or inputs from the user.
Example 8.1
<form name=”myForm” method=”get”
action=”f.php”>
<input name=”txt” type=”text”>
<input name=”pwd” type=”password”>
<input name=”rd” type=”radio”
value=”val2”>
<input name=”chkb” type=”checkbox”
value=”val3”>
<input name=”sbmt” type=”submit”
value=”Submit”>
<input name=”rst” type=”reset”
value=”Cancel”>
</form>
Explanation:
“name” means a name of the element.
“method=”get/post”” means the data
send by “get” or “post”.
“get” method sends data openly, small
quantity.
“post” method sends data secretly, more
quantity.
“action=f.php” means the data will be
processed by f.php
“type” specify the type of element.
The Element of the
form
“document.formName.elementName.type
the element type. such as text, radio, chec
“document.formName.elements["Name"]
// returns the element type. such as te
checkbox…
Example 8.2
<html>
<body>
<form name="myForm">
1.<input type="text" name="txt" />
<br>
2.<input type="radio" name="rd" />
<br>
3.<input type="checkBox"
name="chkb" /><br>
4.<input type="password"
name="pwd" /><br>
5.<select name="select"></select>
<br>
6.<textarea name="area"></textarea>
<br>
7.<input type="submit"
name="submit" /><br>
</form>
<script type="text/javascript">
document.write("The 1st element is: "
+document.myForm.txt.type+"
<br>");
document.write("The 2nd element is: "
+document.myForm.rd.type+"<br>");
alert(object.value);
“document.write(object.value);” and
“alert(object.value);” can show the
value of an element.
Example 8.5
<html>
<head>
<title>JavaScript Codes</title>
</head>
<body>
<br><br>
<center>
<form>
<button id="myButton"
value="12345678">Button</button>
</form>
</center>
<script type="text/javascript">
var button =
document.getElementById('myButton');
button.onclick = function(){
document.write ( button.value ); //
show button value
alert ( button.value ); // show button
value
}
</script>
</body>
</html>
Output:
12345678
12345678
Explanation:
“button id="myButton"
value="12345678"” sets the value of the
button as “12345678”.
“document.write(button.value);” and
“alert(button.value);” show the button’s
value.
Input Data to Form
document.formName.elementName.value
“document.formname.elementName.value”
can get or set value for the specified
element.
Example 8.7
<html>
<head>
<title>JavaScript Codes</title>
</head>
<body>
<br><br>
<center>
<form name="myForm">
<input type="text" name="myText"
value="" />
<input type="submit"
onClick="show()">
</form>
</center>
<script type="text/javascript">
function show(){
alert("You have inputted: " +
document.myForm.myText.value); /*
gets the value of data which the user has
inputted */
}
</script>
</body>
</html>
Output:
(Show what user has inputted.)
Explanation:
“document.myForm.myText.value” gets
the value of the text field, to which user
has inputted data.
Reset Method
reset( )
“reset( )” is used to clear the form data.
Example 8.8
<html>
<head>
<title>JavaScript Codes</title>
</head>
<body>
<br><br>
<center>
<form id="myform" >
<textarea></textarea>
<br><br>
<input type="button"
onclick="myfunction()" value="Clear" >
</form>
</center>
<script type="text/javascript">
function myfunction() {
document.getElementById("myform").r
// “reset( )” clears “myform” data
}
</script>
</body>
</html>
Output:
( The form data are completely cleared.)
Explanation:
“onclick="myfunction()” executes the
myfunction( ) immediately when clicking
the button.
“getElementById("myform")” access the
“myform” by its id.
“reset( )” clears “myform” data.
Submit Method
submit( )
“submit( )” is used to submit the form
data to server.
Example 8.9
<html>
<body>
<br><br>
<center>
<form id="myform" action="">
<textarea></textarea>
<br><br>
<input type="button"
onclick="myfunction()" value="submit"
>
</form>
</center>
<script type="text/javascript">
function myfunction() {
document.getElementById("myform").s
// “submit( )” submits “myform” data to
server.
alert("All data have been submitted
successfully!");
}
</script>
</body>
</html>
Output:
All data have been submitted
successfully!
Explanation:
“onclick="myfunction()” executes the
myfunction( ) immediately when clicking
the button.
“getElementById("myform")” access the
“myform” by its id.
“submit( )” submits “myform” data to
server.
“Select” Selection
<select id="myID " onchange="function (
When a “select” value in form is
changed, “onChange” event occurs and
runs the “function ( )” at once.
Red
Example 8.10
<html>
<head>
<script language="javascript">
function choose(color){
alert("The traffic light is "+ color);
}
</script>
</head>
<body>
<br><br>
<center>
<form id="myForm">
<select name="trafficLight"
onChange="choose(this.value)">
<!- - runs the function “choose()” when
selecting an option - ->
<option value="Red">Red</option>
<option
value="Yellow">Yellow</option>
<option value="Green">Green</option>
</select>
</form>
</center>
</body>
</html>
Output:
The traffic light is Green.
Explanation:
<select name="trafficLight"
onChange="choose(this.value)"> runs
the function “choose()” when selecting
an option, and pass the parameter “this
value” to alert( ).
“Radio” Selection
appendClild( );
“window.document.createElement( )”
creates an element node with the
specified name.
“appendClild( )” appends a node as the
last child node.
Example 8.14
<html>
<body>
<br><br>
<center>
<script>
var myLine =
document.createElement("hr");
// creates an element node “hr”, a
horizontal ruled line tag
document.body.appendChild(myLine);
// appends “myLine” element to the
HTML document body.
</script>
</center>
</body>
</html>
Output:
----------------------------------------------
---------
Explanation:
“myLine =
document.createElement("hr")” creates
an element node named “myLine”.
“hr” is a horizontal ruled line tag.
“document.body.appendChild(myLine)”
appends “myLine” element in the HTML
document body.
DOM:
CreateTextNode( )
window.document.createTextNode( );
appendChild( );
“window.document.createTextNode( )”
creates a text node with the specified
text.
“appendClild( )” appends a node as the
last child node.
Example 8.15
<html>
<body>
<br><br>
<center>
<script>
var myText =
document.createTextNode("Hello
Dom!");
// creates a text node named “myText”.
document.body.appendChild(myText);
// appends “myText” text node in the
HTML document body.
</script>
</center>
</body>
</html>
Output:
Hello Dom!
Explanation:
“myText =
document.createTextNode("Hello
Dom!")” creates a text node named
“myText”.
“Hello Dom!” is a specified string.
“document.body.appendChild(myText)”
appends “myText” text node in the
HTML document body.
DOM:
set/getAttribute( )
getAttribute( attributeName );
“setAttribute( attributeName, value)”
adds the specified attribute and
specified value to an element.
“getAttribute( attributeName )” returns
the value of a specified attribute on an
element.
Example 8.16
<html>
<head>
<title>
Dom
</title>
</head>
<body>
<br>
<p>Hello Dom!</p><br>
<center>
<script>
var s =
document.getElementsByTagName("p")
[0];
s.setAttribute("align", "center"); //
set align as center
</script>
</center>
</body>
</html>
Output:
Hello Dom!
Explanation:
“align” is an attribute name, “center” is
an attribute value.
“s.setAttribute("align", "center")” sets
the attribute of “s” object.
Example 8.17
<html>
<head>
<style>
.setColor {
color: green;
}
</style>
</head>
<body>
<br>
<center>
<p class="setColor">Hello Dom!</p>
<br>
<!- - attribute name is “class”, attribute
value is “setColor”- ->
<script>
var g =
document.getElementsByTagName("p")
[0]; // first p
var attr = g.getAttribute( "class" ); //
get class value
document.write( "The attribute is: " +
attr );
</script>
</center>
</body>
</html>
Output:
Hello Dom!
The attribute is: setColor
Explanation:
“class” is an attribute name, “setColor”
is an attribute value.
“g.getAttribute( "class" )” gets the
attribute value of “g” object.
DOM:
hasChildNodes( )
hasChildNodes ( )
“hasChildNodes( )” returns true if the
specified node has any child nodes,
otherwise returns false.
Example 8.18
<html>
<head>
<title>
Dom
</title>
</head>
<body>
<br><br>
Color
<ul id="color">
<li>Green</li>
<li>Yellow</li>
<li>Red</li>
</ul>
<script>
var child =
document.getElementById("color").has
);
// check if the “color” id has nested
child elements
alert ("Color has some child nodes? " +
child );
</script>
</body>
</html>
Output:
Color has some child nodes? true
Explanation:
“hasChildNodes( )” tests to see if the
“color” id has nested child elements.
Because “color” id contains three child
elements “Green”, “Yellow” and “Red”,
it returns true.
Hands-On Project:
Clear Anything
Form Reset
Open Notepad, write JavaScript codes:
<html>
<body>
<center>
<form id="myForm" method="get"
action="xxx.php">
<br><br>
Username: <input type="text",id="txt1"
/><br><br>
Password: <input type="text",id="txt2"
/><br><br>
<input type="button" value="Reset"
onClick="doReset()"/>
<script>
function doReset(){
var myForm=
document.getElementById("myForm");
myForm.reset(); // clear any input
data
}
</script>
</center>
</body>
</html>
Output:
Explanation:
“onClick="doReset()” executes the
function “doDoset( )” when clicking the
button.
“myForm.reset();” clears all data in
myForm, and restore the original values.
Appendix
JavaScript 100
Tests & Answers
100 Tests
1. Which following tags is for
JavaScript?
1. <?……?>
2. <JavaScript…...>…..</JavaScript>
3. <script
Language=”JavaScript”>……
</JavaScript>
4. <script type =
“text/JavaScript”>……</script>
1. line1.
2. line2.
3. line3
4. line4
A. true
B. false
C. 1
D. -1.
18. What is the result in the following
code?
var x = 0, y = 50;
while ( x < 10) {
y--;
x++;
}
alert ( "x is: " + x + " and y is: " + y);
1. x is 10 and y is 40
2. x is 11 and y is 41
3. x is 12 and y is 42
4. x is 13 and y is 43
19. What is output in the following
code?
var x = 0, y = 50;
do {
y--;
x++;
} while ( x < 10)
alert ( "x is: " + x + " and y is: " + y);
1. x is 13 and y is 43
2. x is 12 and y is 42
3. x is 11 and y is 41
4. x is 10 and y is 40
20. What is the output in the following
code?
for (var num = 1; num < 10; num ++) {
document.write ( num + " " );
if (num % 5 == 0)
break;
1. 12
2. 123
3. 1234
4. 12345
21. What is the output in the following
code?
for (var num = 1; num < 7; num++) {
if (num == 5)
continue;
document.write ( num + " " );
}
1. 12345
2. 12346
3. 12347
4. 12348
1. aSc
2. Scr
3. aScrp
4. Script
1. 300
2. 200
3. error
4. 100200
41. Which line is not correct in the
following code?
var num = 100; // line 1
if ( NaN )== num){ // line 2
num++; // line 3
alert( num); //line 4
}
1. line 1
2. line 2
3. line 3
4. line 4
42. Which line is not correct in the
following code?
var str1 = "JavaScript"; // line 1
var str2 = "is very good."; // line 2
var myString = str1 + str2; // line 3
document.write ( myString.length( )); //
line 4
1. line 1
2. line 2
3. line 3
4. line 4
1. 2550
2. 1275
3. 637.5
4. 318.75
1. myText
2. TextNode
3. appenChild
4. Hello Dom!
97. What is the output in the following
code?
<p>Hello Dom!</p><br>
<script>
var s =
document.getElementsByTagName("p")
[0];
s.setAttribute("align", "center");
</script>
Dear My Friend,
If you are not satisfied with this eBook,
could you please return the eBook for a
refund within seven days of the date of
purchase?
If you found any errors in this book,
could you please send an email to me?
[email protected]
I will be very grateful for your email.
Thank you very much!
Sincerely
Ray Yao