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

JavaScript Overview and Basics Guide

JavaScript is a lightweight, interpreted programming language initially named LiveScript, designed for creating interactive web applications. It allows client-side scripting, enabling dynamic content and user interaction without heavy server reliance, although it has limitations such as lack of file access and multithreading. The document also covers JavaScript syntax, variables, data types, and development tools, along with instructions for enabling JavaScript in various browsers.

Uploaded by

tommyassefa95
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views161 pages

JavaScript Overview and Basics Guide

JavaScript is a lightweight, interpreted programming language initially named LiveScript, designed for creating interactive web applications. It allows client-side scripting, enabling dynamic content and user interaction without heavy server reliance, although it has limitations such as lack of file access and multithreading. The document also covers JavaScript syntax, variables, data types, and development tools, along with instructions for enabling JavaScript in various browsers.

Uploaded by

tommyassefa95
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter-5

Java Script

Compiled by: Gebremedhin, Lecturer,AKU


JavaScript Overview
What is JavaScript ?

 JavaScript started life as LiveScript, but Netscape changed the name, possibly because of
the excitement being generated by [Link] JavaScript. JavaScript made its first appearance
in Netscape 2.0 in 1995 with a name LiveScript.

 JavaScript is a lightweight, interpreted programming language with object-oriented


capabilities

 the language has been embedded in Netscape, Internet Explorer, and other web browsers

JavaScript is:

 JavaScript is a lightweight, interpreted programming language

 Designed for creating network-centric applications

 Complementary to and integrated with Java

 Complementary to and integrated with HTML


 Open and cross-platform
Client-side JavaScript:
 Client-side JavaScript is the most common form of the language.

 The script should be included in or referenced by an HTML document for the code to be
interpreted by the browser.

 It means that a web page need no longer be static HTML, but can include programs that
interact with the user, control the browser, and dynamically create HTML content.

 The JavaScript client-side mechanism features many advantages over traditional server-
side scripts. For example, you might use JavaScript to check if the user has entered a valid
e-mail address in a form field.

 The JavaScript code is executed when the user submits the form, and only if all the entries
are valid they would be submitted to the Web Server.

 JavaScript can be used to trap user-initiated events such as button clicks, link navigation,
and other actions that the user explicitly or implicitly initiates.
Advantages of JavaScript:
 Less server interaction: You can validate user input
before sending the page off to the server.
 This saves server traffic, which means less load on
your server.
 Immediate feedback to the visitors: They don't have
to wait for a page reload to see if they have forgotten
to enter something.
 Increased interactivity: You can create interfaces that
react when the user hovers over them with a mouse
or activates them via the keyboard.
 Richer interfaces: You can use JavaScript to include
such items as drag-and-drop components and sliders
to give a Rich Interface to your site visitors.
Limitations with JavaScript:
 We can not treat JavaScript as a full fledged programming
language. It lacks the following important features:

 Client-side JavaScript does not allow the reading or writing of files.


This has been kept for security reason.

 JavaScript can not be used for Networking applications because


there is no such support available.

 JavaScript doesn't have any multithreading or multiprocess


capabilities.

 JavaScript is a lightweight, interpreted programming language that


allows you to build interactivity into otherwise static HTML pages.
JavaScript Development Tools:

 One of JavaScript's strengths is that expensive development tools are not usually required. You can
start with a simple text editor such as Notepad.

 Since it is an interpreted language inside the context of a web browser, you don't even need to buy a
compiler.

 To make our life simpler, various vendors have come up with very nice JavaScript editing tools. Few
of them are listed here:

 Microsoft FrontPage: Microsoft has developed a popular HTML editor called FrontPage. FrontPage
also provides web developers with a number of JavaScript tools to assist in the creation of an
interactive web site.

 Macromedia Dreamweaver MX: Macromedia Dreamweaver MX is a very popular HTML and


JavaScript editor in the professional web development crowd. It provides several handy prebuilt
JavaScript components, integrates well with databases, and conforms to new standards such as
XHTML and XML.

 Macromedia HomeSite 5: This provided a well-liked HTML and JavaScript editor, which will
manage their personal web site just fine.
Where JavaScript is Today ?
 The ECMAScript Edition 4 standard will be the first update
to be released in over four years. JavaScript 2.0 conforms to
Edition 4 of the ECMAScript standard, and the difference
between the two is extremely minor.
 The specification for JavaScript 2.0 can be found on the
following site: [Link]
 Today, Netscape's JavaScript and Microsoft's JScript conform
to the ECMAScript standard, although each language still
supports features that are not part of the standard.
JavaScript Syntax
 A JavaScript consists of JavaScript statements that are
placed within the <script>... </script> HTML tags in a
web page.

 You can place the <script> tag containing your


JavaScript anywhere within you web page but it is
preferred way to keep it within the <head> tags.

 The <script> tag alert the browser program to begin


interpreting all the text between these tags as a script.
• So simple syntax of your JavaScript will be as follows
<script ...>
JavaScript code
</script>
 The script tag takes two important attributes:
 language: This attribute specifies what scripting language
you are using. Typically, its value will be javascript.
Although recent versions of HTML (and XHTML, its
successor) have phased out the use of this attribute.
 type: This attribute is what is now recommended to indicate
the scripting language in use and its value should be set to
"text/javascript".
 So your JavaScript segment will look like:

<script language="javascript― type="text/javascript">

JavaScript code

</script>
Your First JavaScript Script:
 Let us write our class example to print out
"Hello World".
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
[Link]("Hello World!")
//-->
</script></body>
</html>
 We added an optional HTML comment that surrounds our
Javascript code.
 This is to save our code from a browser that does not support
Javascript.
 The comment ends with a "//-->". Here "//" signifies a comment in
Javascript, so we add that to prevent a browser from reading the
end of the HTML comment in as a piece of Javascript code.
 Next, we call a function [Link] which writes a string into
our HTML document.
 This function can be used to write text, HTML, or both. So above
code will display following result:
Hello World!
Whitespace and Line Breaks:

JavaScript ignores spaces, tabs, and newlines that


appear in JavaScript programs.

Because you can use spaces, tabs, and newlines


freely in your program so you are free to format
and indent your programs in a neat and consistent
way that makes the code easy to read and
understand.
Semicolons are Optional:
 Simple statements in JavaScript are generally followed by a
semicolon character, just as they are in C, C++, and Java.
 JavaScript, however, allows you to omit this semicolon if your
statements are each placed on a separate line.
 For example, the following code could be written without
semicolons
<script language="javascript" type="text/javascript">
<!–
var1 = 10
var2 = 20
//-->
</script>
But when formatted in a single line as follows, the
semicolons are required:
<script language="javascript" type="text/javascript">
<!-- var1 = 10; var2 = 20;
//-->
</script>
Note: It is a good programming practice to use
semicolons.
Case Sensitivity:
 JavaScript is a case-sensitive language.

 This means that language keywords, variables,


function names, and any other identifiers must always
be typed with a consistent capitalization of letters.

 So identifiers Time, TIme and TIME will have different


meanings in JavaScript.

 NOTE: Care should be taken while writing your


variable and function names in JavaScript.
Comments in JavaScript:
 JavaScript supports both C-style and C++-style comments, Thus:
 Any text between a // and the end of a line is treated as a comment
and is ignored by JavaScript.
 Any text between the characters /* and */ is treated as a
comment. This may span multiple lines.
 JavaScript also recognizes the HTML comment opening
sequence <!--. JavaScript treats this as a single-line comment,
just as it does the // comment.
 The HTML comment closing sequence --> is not recognized by
JavaScript so it should be written as //-->.
Example:
<script language="javascript― type="text/javascript">
<!—
// This is a comment. It is similar to comments in C++
/*
 This is a multiline comment in JavaScript
 It is very similar to comments in C Programming
*/
//-->
</script>
Enabling JavaScript in Browsers
 All the modern browsers come with built-in support
for JavaScript.
 Many times you may need to enable or disable this
support manually.
 This course will make you aware the procedure of
enabling and disabling JavaScript support in your
browsers :
 Internet Explorer,
 Firefox and Opera.
JavaScript in Internet Explorer:
Here are simple steps to turn on or turn off JavaScript in your Internet
Explorer:
 Follow Tools-> Internet Options from the menu
 Select Security tab from the dialog box
 Click the Custom Level button
 Scroll down till you find Scripting option
 Select Enable radio button under Active scripting
 Finally click OK and come out
 To disable JavaScript support in your Internet Explorer, you need to select
Disable radio button under Active scripting.
JavaScript in Firefox:
 Here are simple steps to turn on or turn off JavaScript in your
Firefox:
 Follow Tools-> Options
 from the menu
 Select Content option from the dialog box
 Select Enable JavaScript checkbox
 Finally click OK and come out
 To disable JavaScript support in your Firefox, you should not
select Enable JavaScript checkbox.
Warning for Non-JavaScript Browsers:
If you have to do something important using JavaScript then you can display a warning
message to the user using <noscript> tags.
You can add a noscript block immediately after the script block as follows:
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
[Link]("Hello World!")
//-->
</script>

<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</body>
</html>
Now, if user's browser does not support JavaScript or JavaScript is not enabled then message
from </noscript> will be displayed on the screen.
JavaScript Placement in HTML File
 There is a flexibility given to include JavaScript code anywhere in an
HTML document.
 But there are following most preferred ways to include JavaScript in your
HTML file.
 Script in <head>...</head> section.
 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in and external file and then include in <head>...</head> section.
 In the following section we will see how we can put JavaScript in different
ways:
JavaScript in <head>...</head> section:
 If you want to have a script run on some event, such as when a user clicks somewhere, then
you will place that script in the head as follows:
<html>
<head><script type="text/javascript">
<!--function sayHello()
{ alert("Hello World")}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
This will produce following result: say Hello
JavaScript in <body>...</body> section:
If you need a script to run as the page loads so that the script generates content in the page, the script goes
in the <body> portion of the document. In this case you would not have any function defined using
JavaScript:
<html>
<head></head>
<body>
<script type="text/javascript">
<!--[Link]("Hello World")
//--></script>
<p>This is web page body </p>
</body>
</html>
This will produce following result:
Hello World
This is web page body
JavaScript Variables and DataTypes
JavaScript DataTypes:
 One of the most fundamental characteristics of a programming language is the set of data types it
supports.

 These are the type of values that can be represented and manipulated in a programming language.

 JavaScript allows you to work with three primitive data types:

1. Numbers eg. 123, 120.50 etc.

2. Strings of text e.g. "This text string" etc.

3. Boolean e.g. true or false.

 JavaScript also defines two trivial data types, null and undefined, each of which defines only a single
value.

 In addition to these primitive data types, JavaScript supports a composite data type known as object.

 Note: Java does not make a distinction between integer values and floating-point values.

 All numbers in JavaScript are represented as floating-point values.

 JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.
JavaScript Variables:
 Like many other programming languages, JavaScript has variables.
 Variables can be thought of as named containers.
 You can place data into these containers and then refer to the data
simply by naming the container.
 Before you use a variable in a JavaScript program, you must declare it.
 Variables are declared with the var keyword as follows:
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>
You can also declare multiple variables with the
same var keyword as follows:

<script type="text/javascript">

<!--

var money, name;

/ /-->

</script>
 Storing a value in a variable is called variable initialization.
 You can do variable initialization at the time of variable creation or later point in
time when you need that variable as follows:
 For instance, you might create a variable named money and assign the value
2000.50 to it later. For another variable you can assign a value the time of
initialization as follows:
<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
 Note: Use the var keyword only for declaration or
initialization.
 once for the life of any variable name in a document. You
should not re-declare same variable twice.
 JavaScript is untyped language. This means that a JavaScript
variable can hold a value of any data type.
 Unlike many other languages, you don't have to tell
JavaScript during variable declaration what type of value the
variable will hold.
 The value type of a variable can change during the execution
of a program and JavaScript takes care of it automatically.
JavaScript Variable Names:
 While naming your variables in JavaScript keep following rules in
mind.
 You should not use any of the JavaScript reserved keyword as
variable name. For example, break or boolean variable names are
not valid.
 JavaScript variable names should not start with a numeral (0-9).
 They must begin with a letter or the underscore character. For
example, 123test is an invalid variable name but _123test is a
valid one.
 JavaScript variable names are case sensitive. For example, Name
and name are two different variables.
JavaScript Operators
What is an operator?
 Simple answer can be given using expression 4 + 5 is equal
to 9.
 Here 4 and 5 are called operands and + is called operator.
 JavaScript language supports following type of operators.
 Arithmetic Operators
 Comparision Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
The Arithmatic Operators:
 There are following arithmatic operators
 supported by JavaScript language:
Assume variable A holds 10 and variable B
holds 20 then:
 Note: Addition operator (+) works for Numeric
as well as Strings. e.g. "a" + 10 will give "a10".
Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiply both operands A * B will give 200

/ Divide numerator by denumerator B / A will give 2

Modulus Operator and remainder of after an


% B % A will give 0
integer division

Increment operator, increases integer value by


++ A++ will give 11
one

Decrement operator, decreases integer value


-- A-- will give 9
by one
The Comparison Operators:
There are following comparison operators
supported by JavaScript language
Assume variable A holds 10 and variable B holds 20
then:
O
perat Description Example
or

= Checks if the value of two operands are equal or


(A == B) is not true.
= not, if yes then condition becomes true.

! Checks if the value of two operands are equal or


not, if values are not equal then condition becomes (A != B) is true.
= true.

Checks if the value of left operand is greater than


> the value of right operand, if yes then condition (A > B) is not true.
becomes true.

Checks if the value of left operand is less than the


< value of right operand, if yes then condition becomes (A < B) is true.
true.

> Checks if the value of left operand is greater than


or equal to the value of right operand, if yes then (A >= B) is not true.
= condition becomes true.

Checks if the value of left operand is less than or


<
equal to the value of right operand, if yes then (A <= B) is true.
=
JavaScript if...else Statements
 While writing a program, there may be a situation when you need to adopt
one path out of the given two paths.

 So you need to make use of conditional statements that allow your program
to make correct decisions and perform right actions.

 JavaScript supports conditional statements which are used to perform


different actions based on different conditions. Here we will explain if..else
statement.

 JavaScript supports following forms of if..else statement:

 if statement

 if...else statement

 if...else if... statement.


if statement
 The if statement is the fundamental control statement that allows
JavaScript to make decisions and execute statements conditionally.

Syntax:

if (expression){

Statement(s) to be executed if expression is true

 Here JavaScript expression is evaluated. If the resulting value is true,


given statement(s) are executed.

 If expression is false then no statement would be not executed. Most of


the times you will use comparison operators while making decisions.
Example:
<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
[Link]("<b>Qualifies for driving</b>");
}
//-->
</script>
This will produce following result:
Qualifies for driving
if...else statement:
 The if...else statement is the next form of control statement that allows

JavaScript to execute statements in more controlled way.

Syntax:

if (expression){

Statement(s) to be executed if expression is true

}else{

Statement(s) to be executed if expression is false

 Here JavaScript expression is evaluated. If the resulting value is true, given

statement(s) in the if block, are executed.

 If expression is false then given statement(s) in the else block, are executed.
Example:

<script type="text/javascript">

<!--

var age = 15;

if( age > 18 ){

[Link]("<b>Qualifies for driving</b>");

}else{

[Link]("<b>Does not qualify for driving</b>");

//-->

</script>

This will produce following result:

Does not qualify for driving


if...else if... statement:
 The if...else if... statement is the one level advance form of control statement that allows
JavaScript to make correct decision out of several conditions.

Syntax:

if (expression 1){

Statement(s) to be executed if expression 1 is true

}else if (expression 2){

Statement(s) to be executed if expression 2 is true

}else if (expression 3){

Statement(s) to be executed if expression 3 is true

}else{

Statement(s) to be executed if no expression is true

}
 There is nothing special about this code.

 It is just a series of if statements, where each if is


part of the else clause of the previous statement.

 Statement(s) are executed based on the true


condition, if non of the condition is true then else
block is executed.
Example:
<script type="text/javascript">
<!--
var book = "maths";
if( book == "history" ){
[Link]("<b>History Book</b>");
}else if( book == "maths" ){
[Link]("<b>Maths Book</b>");
}else if( book == "economics" ){
[Link]("<b>Economics Book</b>");
}else{
[Link]("<b>Unknown Book</b>");
}
//-->
</script>

This will produce following result:


Maths Book
JavaScript Switch Case
You can use multiple if...else if statements, as in
the previous , to perform a multi way branch.

However, this is not always the best solution,


especially when all of the branches depend on the
value of a single variable.

 you can use a switch statement which handles


exactly this situation, and it does so more
efficiently than repeated if...else if statements.
Syntax:
The basic syntax of the switch statement is to give
an expression to evaluate and several different
statements to execute based on the value of the
expression.
The interpreter checks each case against the value
of the expression until a match is found.
 If nothing matches, a default condition will be
used.
switch (expression){
case condition 1: statement(s)
break;
case condition 2: statement(s)
break; ...
case condition n: statement(s)
break;
default: statement(s)
}
 The break statements indicate to the interpreter the end of that particular case.
 If they were omitted, the interpreter would continue executing each statement in
each of the following cases.
 We will explain break statement in Loop Control next
Example:
<script type="text/javascript">
<!--
var grade='A';
[Link]("Entering switch block<br />");
switch (grade){
case 'A': [Link]("Good job<br />");
break;
case 'B': [Link]("Pretty good<br />");
break;
case 'C': [Link]("Passed<br />");
break;
case 'D': [Link]("Not so good<br />");
break;
case 'F': [Link]("Failed<br />");
break;
default: [Link]("Unknown grade<br />")}
[Link]("Exiting switch block");
//--></script>
This will produce following result:
Entering switch block
Good job
Exiting switch block

Example:

Consider a case if you do not use break statement:


<script type="text/javascript">
<!--
var grade='A';
[Link]("Entering switch block<br />");
switch (grade){
case 'A': [Link]("Good job<br />");
case 'B': [Link]("Pretty good<br />");
case 'C': [Link]("Passed<br />");
case 'D': [Link]("Not so good<br />");
case 'F': [Link]("Failed<br />");
default: [Link]("Unknown grade<br />");
}
[Link]("Exiting switch block");
//-->
</script>
This will produce following result:
Entering switch block
Good job
Pretty good
Passed
Not so good
Failed
Unknown grade
Exiting switch block
JavaScript while Loops
 While writing a program, there may be a situation
when you need to perform some action over and over
again.
 In such situation you would need to write loop
statements to reduce the number of lines.
 JavaScript supports all the necessary loops to help you
on all steps of programming.
The while Loop
 The most basic loop in JavaScript is the while loop.
Syntax:

while (expression)

{ Statement(s) to be executed if expression is true}

The purpose of a while loop is to execute a


statement or code block repeatedly as long as
expression is true.

Once expression becomes false, the loop will be


exited.
Example:
Following example illustrates a basic while loop:
<script type="text/javascript">
<!--
var count = 0;
[Link]("Starting Loop" + "<br />");
while (count < 10){
[Link]("Current Count : " + count + "<br />");
count++;
}
[Link]("Loop stopped!");
//-->
</script>
This will produce following result:
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
The do...while Loop:
 The do...while loop is similar to the while loop except
that the condition check happens at the end of the loop.
 This means that the loop will always be executed at
least once, even if the condition is false.
Syntax:
do{
Statement(s) to be executed;}
while (expression);

Note the semicolon used at the end of the do...while


loop.
Example:
Let us write above example in terms of do...while loop.
<script type="text/javascript">
<!--
var count = 0;
[Link]("Starting Loop" + "<br />");
do{
[Link]("Current Count : " + count + "<br />");
count++;
}
while (count < 0);
[Link]("Loop stopped!");
//-->
</script>
This will produce following result:
Starting Loop
Current Count : 0
Loop stopped!
JavaScript for Loops
 We have seen different variants of while loop. another popular loop called for loop.

The for Loop


 The for loop is the most compact form of looping and includes the following three
important parts:
 The loop initialization where we initialize our counter to a starting value.
 The initialization statement is executed before the loop begins.
 The test statement which will test if the given condition is true or not.
 If condition is true then code given inside the loop will be executed otherwise loop
will come out.
 The iteration statement where you can increase or decrease your counter.
 You can put all the three parts in a single line separated by a semicolon.
Syntax:
for (initialization; test condition; iteration
statement){
Statement(s) to be executed if test condition is
true
}

Example:

Following example illustrates a basic for loop:


<script type="text/javascript">

<!--

var count;

[Link]("Starting Loop" + "<br />");

for(count = 0; count < 10; count++){

[Link]("Current Count : " + count );

[Link]("<br />");

[Link]("Loop stopped!");

//-->

</script>
This will produce following result which is similar to while loop:

Starting Loop

Current Count : 0

Current Count : 1

Current Count : 2

Current Count : 3

Current Count : 4

Current Count : 5

Current Count : 6

Current Count : 7

Current Count : 8

Current Count : 9

Loop stopped!
JavaScript Loop Control

 JavaScript provides you full control to handle your loops and


switch statement.

 There may be a situation when you need to come out of a loop without
reaching at its bottom.

 There may also be a situation when you want to skip a part of your
code block and want to start next iteration of the look.

 To handle all such situations, JavaScript provides break and continue


statements.

 These statements are used to immediately come out of any loop or to
start the next iteration of any loop respectively.
The break Statement:

 The break statement, which was briefly introduced


with the switch statement, is used to exit a loop early,
breaking out of the enclosing curly braces.

Example:
 This example illustrates the use of a break statement
with a while loop.
 Notice how the loop breaks out early once x reaches
5 and reaches to [Link](..) statement just
below to closing curly brace:
<script type="text/javascript">
<!--
var x = 1;
[Link]("Entering the loop<br /> ");
while (x < 20){
if (x == 5){
break;
// breaks out of loop completely
}
x = x + 1;
[Link]( x + "<br />");
}
[Link]("Exiting the loop!<br /> ");
//-->
</script>
This will produce following result:

Entering the loop

Exiting the loop!


The continue Statement:
 The continue statement tells the interpreter to immediately start the
next iteration of the loop and skip remaining code block.
 When a continue statement is encountered, program flow will move
to the loop check expression immediately and if condition remain
true then it start next iteration otherwise control comes out of the
loop.
Example:
 This example illustrates the use of a continue statement with a while
loop.
 Notice how the continue statement is used to skip printing when the
index held in variable x reaches 5:
<script type="text/javascript">
<!--
var x = 1;
[Link]("Entering the loop<br /> ");
while (x < 10){
x = x + 1;
if (x == 5){
continue;
// skill rest of the loop body
}
[Link]( x + "<br />");
}
[Link]("Exiting the loop!<br /> ");
//-->
</script>
This will produce following result:
Entering the loop
2
3
4
6
7
8
9
10
Exiting the loop!
JavaScript Functions
 A function is a group of reusable code which can be called anywhere
in your programme.

 This eliminates the need of writing same code again and again.

 This will help programmers to write modular code.

 You can divide your big programme in a number of small and


manageable functions.

 Like any other advance programming language, JavaScript also


supports all the features necessary to write modular code using
functions.
We are using these function again and again but
they have been written in core JavaScript only
once.
JavaScript allows us to write our own functions as
well.
Function Definition

 The most common way to define a function in JavaScript is by


using the function keyword, followed by a unique function
name, a list of parameters (that might be empty), and a
statement block surrounded by curly braces.
The basic syntax is shown here:
<script type="text/javascript">
<!--
function functionname(parameter-list)
{
statements}
//-->
</script>
Example:
A simple function that takes no parameters called sayHello is
defined here:
<script type="text/javascript">
<!--
function sayHello()
{
alert("Hello there");
}
//-->
</script>
Calling a Function: To invoke a function
somewhere later in the script, you would simple
need to write the name of that function as follows:

<script type="text/javascript">

<!--

sayHello();

//-->

</script>
Function Parameters:
 Till now we have seen function without a parameters.
 But there is a facility to pass different parameters
while calling a function.
 These passed parameters can be captured inside the
function and any manipulation can be done over those
parameters.
 A function can take multiple parameters separated by
comma.
Example:
Let us do a bit modification in our sayHello function.
This time it will take two parameters:
<script type="text/javascript">
<!--
function sayHello(name, age)
{
alert( name + " is " + age + " years old.");
}
//-->
sayHello('Zara', 7 );
</script>
Note: We are using + operator to concatenate string and
number all together.
JavaScript does not mind in adding numbers into strings.
Now we can call this function as follows:
<script type="text/javascript">
<!--
sayHello('Zara', 7 );
//-->
</script>
The return Statement:

 A JavaScript function can have an optional return statement.

 This is required if you want to return a value from a function.

 This statement should be the last statement in a function.

 For example you can pass two numbers in a function and then
you can expect from the function to return their multiplication
in your calling program.

Example:

 This function takes two parameters and concatenates them


and return resultant in the calling program.
<script type="text/javascript">
<!--
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}
//-->
</script>
Now we can call this function as follows:
<script type="text/javascript">

<!–

var result;

result = concatenate('Zara', 'Ali');

alert(result );

//-->

</script>
JavaScript Events

What is an Event ?

 JavaScript's interaction with HTML is handled through events that occur


when the user or browser manipulates a page.

 When the page loads, that is an event.

 When the user clicks a button, that click, too, is an event.

 Another example of events are like pressing any key, closing window,
resizing window etc.

 Developers can use these events to execute JavaScript coded responses,


which cause buttons to close windows, messages to be displayed to users,
data to be validated, and virtually any other type of response imaginable
to occur.
 Events are a part of the Document Object Model (DOM) Level 3
and every HTML element have a certain set of events which can
trigger JavaScript Code.

 Here we will see few examples to understand a relation between


Event and JavaScript:

1. onclick Event Type:


 This is the most frequently used event type which occurs when a
user clicks mouse left button.
 You can put your validation, warning etc against this event type.
Example:
<html>
<head>
<script type="text/javascript">
<!--
function sayHello()
{
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say
Hello" />
</body>
</html>
This will produce following result and when
you click Hello button then onclick event will
occur which will trigger sayHello() function.

Say Hello
2. onsubmit event type:
 Another most important event type is onsubmit.
 This event occurs when you try to submit a form.
 So you can put your form validation against this event
type.
 Here is simple example showing its usage.
 Here we are calling a validate() function before
submitting a form data to the webserver.
 If validate() function returns true the form will be
submitted otherwise it will not submit the data.
Example:
<html><head>
<script type="text/javascript">
<!--
function validation()
{
all validation goes here ......... return either true or false
}
//-->
</script>
</head>
<body>
<form method="POST" action="[Link]" onsubmit="return
validate()".......
<input type="submit" value="Submit" />
</form></body></html>
3. onmouseover and onmouseout:
 These two event types will help you to create nice
effects with images or even with text as well.
 The onmouseover event occurs when you bring your
mouse over any element and the onmouseout occurs
when you take your mouse out from that element.
 Example:
 Following example shows how a division reacts
when we bring our mouse in that division:
<html><head>
<script type="text/javascript">
<!--
function over()
{
alert("Mouse Over");
}
function out()
{
alert("Mouse Out");
}//-->
</script>
</head>
<body>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2></div></body></html>
You can change different images using these two event types or you can create help
baloon to help your users.
JavaScript and Cookies
What are Cookies ?
 Web Browser and Server use HTTP protocol to communicate and
HTTP is a stateless protocol.
 But for a commercial website it is required to maintain session
information among different pages.
 For example one user registration ends after completing many pages.
 But how to maintain user's session information across all the web
pages.
 In many situations, using cookies is the most efficient method of
remembering and tracking preferences, purchases, commissions, and
other information required for better visitor experience or site
statistics.
How It Works ?
 Your server sends some data to the visitor's browser in the form of a
cookie. The browser may accept the cookie.

 If it does, it is stored as a plain text record on the visitor's hard drive.

 Now, when the visitor arrives at another page on your site, the
browser sends the same cookie to the server for retrieval.

 Once retrieved, your server knows/remembers what was stored


earlier. Cookies are a plain text data record of 5 variable-length fields:

 Expires : The date the cookie will expire. If this is blank, the cookie
will expire when the visitor quits the browser.
 Domain : The domain name of your site.

 Path : The path to the directory or web page that set the cookie. This may be blank
if you want to retrieve the cookie from any directory or page.

 Secure : If this field contains the word "secure" then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists.

 Name=Value : Cookies are set and retrieved in the form of key and value pairs.

 Cookies were originally designed for CGI programming and cookies' data is
automatically transmitted between the web browser and web server, so CGI scripts
on the server can read and write cookie values that are stored on the client.

 JavaScript can also manipulate cookies using the cookie property of the Document
object. JavaScript can read, create, modify, and delete the cookie or cookies that
apply to the current web page.
Storing Cookies:

 The simplest way to create a cookie is to assign a string


value to the [Link] object, which looks like
this:

Syntax:

 [Link] =
"key1=value1;key2=value2;expires=date";
 Here expires attribute is optional. If you provide this attribute
with a valid date or time then cookie will expire at the given date
or time and after that cookies' value will not be accessible.
 Note: Cookie values may not include semicolons, commas, or
whitespace. For this reason, you may want to use the JavaScript
escape() function to encode the value before storing it in the
cookie. If you do this, you will also have to use the
corresponding unescape() function when you read the cookie
value.
Example:
 Following is the example to set a customer name in input cookie
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
if( [Link] == "" ){
alert("Enter some value!");
return;
}

cookievalue= escape([Link]) + ";";


[Link]="name=" + cookievalue;
alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
</body>
</html>
 This will produce following result. Now enter something in
the text box and press the button "Set Cookie" to set the
cookies.

enter name Set name

 Now your machine has a cookie called name.

 You can set multiple cookies using multiple key=value


pairs separated by comma.
 JavaScript supports three important types of dialog boxes.
These dialog boxes can be used to raise and alert, or to get
confirmation on any input or to have a kind of input from
the users. Here we will see each dialog box one by one:

1. Alert Dialog Box:

 An alert dialog box is mostly used to give a warning


message to the users. Like if one input field requires to
enter some text but user does not enter that field then as a
part of validation you can use alert box to give warning
message as follows:
<head>
<script type="text/javascript">
<!--
alert("Warning Message");
//-->
</script> </head>
 Nonetheless, an alert box can still be used for friendlier
messages. Alert box gives only one button "OK" to select
and proceed.
2. Confirmation Dialog Box:

 A confirmation dialog box is mostly used to take user's


consent on any option. It displays a dialog box with two
buttons: OK and Cancel.

 If the user clicks on OK button the window method


confirm() will return true. If the user clicks on the Cancel
button confirm() returns false. You can use confirmation
dialog box as follows:
<html>
<head>
<script type="text/javascript">
<!--
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
alert("User wants to continue!");
return true;
}else{
alert("User does not want to continue!");
return false; }
//-->
</script>
</head>
</html>
3. Prompt Dialog Box:

 The prompt dialog box is very useful when you want to pop-up a text
box to get user input. Thus it enable you to interact with the user. The
user needs to fill in the field and then click OK.

 This dialog box is displayed using a method called prompt() which


takes two parameters

(i) A label which you want to display in the text box

(ii) A default string to display in the text box.

 This dialog box with two buttons: OK and Cancel. If the user clicks on
OK button the window method prompt() will return entered value
from the text box. If the user clicks on the Cancel button the window
method prompt() returns null.
You can use prompt dialog box as follows:
<head>
<script type="text/javascript">
<!--
var retVal = prompt("Enter your name : ", "your name
here");
alert("You have entered : " + retVal );
//-->
</script>
</head>
Javascript Objects Overview
 JavaScript is an Object Oriented Programming (OOP) language. A
programming language can be called object-oriented if it provides
four basic capabilities to developers:
 Encapsulation: the capability to store related information, whether
data or methods, together in an object
 Aggregation: the capability to store one object inside of another
object
 Inheritance: the capability of a class to rely upon another class (or
number of classes) for some of its properties and methods
 Polymorphism: the capability to write one function or method that
works in a variety of different ways
 Objects are a peace of data that has property and method. For
example myself sofi as an object has properties such as hair color,
height, weight, mane, age etc,…

 Methods are that I do: teaching, driving car, make tutorials, etc

Example
<html> <head> <title> me as objects</title>
<script type="text/javascript">
var teacher = "sofonias Yitagesu";
</script>
</head>
<body>
<script type="text/javascript">
[Link](“our IP1 teacher’s name is : " + teacher + "<br>");
</script> </body> </html>
 You have already learned that JavaScript variables are containers for
data values. This code assigns a simple value (Fiat) to a variable
named car:

var car = "Fiat";

 Objects are variables too. But objects can contain many values.

 This code assigns many values (Fiat, 500, white) to a variable named
car:

var car = {type:"Fiat", model:500, color:"white"};

 The values are written as name: value pairs (name and value
separated by a colon). JavaScript objects are containers for named
values.
Object Properties
 The name:values pairs (in JavaScript objects) are called properties.

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


eyeColor:"blue"};

Property Property Value

firstName John

lastName Doe

age 50

eyeColor Blue
Real Life Objects, Properties, and Methods
 In real life, a car is an object. A car has properties like weight and
color, and methods like start and stop:
 All cars have the same properties, but the property values differ from
car to car. All cars have the same methods, but the methods are
performed at different times.

Object Properties Methods

[Link] = Fiat [Link]()

[Link] = 500 [Link]()


Car
[Link] = 850kg [Link]()

[Link] = white [Link]()


 Object properties can be any of the three primitive data types, or any
of the abstract data types, such as another object. Object properties
are usually variables that are used internally in the object's methods,
but can also be globally visible variables that are used throughout the
page.

 The syntax for adding a property to an object is:

[Link] = propertyValue;

Example:

 Following is a simple example to show how to get a document title


using "title" property of document object:

var str = [Link];


Object Methods
 Methods are actions that can be performed on objects. Methods are
stored in properties as function definitions.

Property Property Value


firstName John

lastName Doe

age 50

eyeColor Blue
function() {
fullName return [Link] + " " + [Link];
}
 The methods are functions that let the object do something or let
something be done to it. There is little difference between a function
and a method, except that a function is a standalone unit of
statements and a method is attached to an object and can be
referenced by the this keyword. Methods are useful for everything
from displaying the contents of the object to the screen to performing
complex mathematical operations on a group of local properties and
parameters. Example:

 Following is a simple example to show how to use write() method of


document object to write any content on the document:

[Link]("This is test");
User-Defined Objects:

 All user-defined objects and built-in objects are descendants of an


object called Object.

The new Operator:

 The new operator is used to create an instance of an object. To create


an object, the new operator is followed by the constructor method.

 In the following example, the constructor methods are Object(),


Array(), and Date(). These constructors are built-in JavaScript
functions.
var employee = new Object();

var books = new Array("C++", "Perl", "Java");

var day = new Date("August 15, 1947");


The Object() Constructor:
 A constructor is a function that creates and initializes an object.
JavaScript provides a special constructor function called Object() to
build the object. The return value of the Object() constructor is
assigned to a variable.

 The variable contains a reference to the new object. The properties


assigned to the object are not variables and are not defined with the
var keyword.

Example 1:

 This example demonstrates how to create an object:


<html>
<head> <title>User-defined objects</title>
<script type="text/javascript">
var book = new Object(); // Create the object
[Link] = "Perl"; // Assign properties to the object
[Link] = "Mohtashim";
</script>
</head>
<body>
<script type="text/javascript">
[Link]("Book name is : " + [Link] + "<br>");
[Link]("Book author is : " + [Link] + "<br>");
</script>
</body>
</html>
Example 2:
This example demonstrates how to create an object with a User-
Defined Function. Here this keyword is used to refer to the object that
has been passed to a function:
<html> <head> <title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
[Link] = title;
[Link] = author;
}
</script> </head> <body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
[Link]("Book title is : " + [Link] + "<br>");
[Link]("Book author is : " + [Link] + "<br>");
</script> </body> </html>
Creating our own object example: with constructor function
<html>
<head> <title> me as objects</title>
<script type="text/javascript">
function person (name, age){
[Link] = name;
[Link] = age;
}
var john = new person (“john yoseph", 29);
var hana = new person (“hana mamo ", 24);
</script>
</head>
<body>
<script type="text/javascript">
[Link]([Link]+"<br/>");
[Link]([Link]);
</script>
</body> </html>
Object Definition
 You define (and create) a JavaScript object with an object literal:

Example

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


eyeColor:"blue"};

 Spaces and line breaks are not important. An object definition can
span multiple lines:
Example
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
Accessing Object Properties
 You can access object properties in two ways:

[Link]

Or

objectName[propertyName]

Example1

[Link];

Example2

person["lastName"];
Accessing Object Methods
 You access an object method with the following syntax:
[Link]()
Example
name = [Link]();
If you access the fullName property, without (), it will return the
function definition:
Example
name = [Link];
Do Not Declare Strings, Numbers, and Booleans as Objects!
When a JavaScript variable is declared with the keyword "new", the
variable is created as an object:
var x = new String(); // Declares x as a String object
var y = new Number(); // Declares y as a Number object
var z = new Boolean(); // Declares z as a Boolean object
Avoid String, Number, and Boolean objects. They complicate your code.
Javascript - The Boolean Object
 The Boolean object represents two values either "true" or "false".

Syntax:

 Creating a boolean object:

var val = new Boolean(value);

 If value parameter is omitted or is 0, -0, null, false, NaN, undefined,


or the empty string (""), the object has an initial value of false.
Javascript - The Number Object
 The Number object represents numerical date, either integers or
floating-point numbers. In general, you do not need to worry about
Number objects because the browser automatically converts
number literals to instances of the number class.

Syntax:

 Creating a number object:

var val = new Number(number);


Javascript -Arrays
 JavaScript arrays are used to store multiple values in a single
variable.
Creating an Array
 We can declare an array like this
var scripts = new Array();
 We can add elements to this array like this
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
 Here is the way to get the third element of an array.
[Link](scripts[2]);
 We also can create an array like this
var no_array = new Array(21, 22, 23, 24, 25); // Array has 5 elements
var my_array=['4th']; // array with single element
Displaying all elements of an array
 We can display all elements of an array by looping through each
element of the array. Here we will increment the index of the array by
one in each loop and display elements of the array one by one. To
identify how many loops we have to make we must know the total
number of elements present inside the array. That we can find out
like this

array_name.length

 So this number we will set as upper limit of our number of rotation or


looping. Here is the code.
var scripts = new Array();
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
for (i=0;i<[Link];i++){
[Link](scripts[i] + "<br >");
}

The for loop in the above code loops through the elements of the array
and display one by one vertically by adding one line break at the end of
each element. The upper limit of the for loop is set to [Link]
value which is in this case equal to 4
 The popular way all the cool kids create arrays these days is to use an open
and close bracket. Below is our groceries variable that is initialized to an
empty array:

var groceries = [];

 You have your variable name on the left, and you have a pair of brackets on
the right that initializes this variable as an empty array. This bracket []
approach for creating an array is better known as the array literal notation.

 Now, you will commonly want to create an array with some items inside it
from the very beginning. To create these non-empty arrays, place the items
you want inside the brackets and separate them by commas:

 var groceries = ["Milk", "Eggs", "Frosted Flakes", "Salami", "Juice"];

 var groceries = new Array(["Milk", "Eggs", "Frosted Flakes",


"Salami", "Juice”);
JavaScript Code: in arrayexample
<script type="text/javascript">

<!–

var myArray = new Array();

myArray[0] = "Football";

myArray[1] = "Baseball";

myArray[2] = "Cricket";

[Link](myArray[0] + myArray[1] + myArray[2]);

//-->

</script>
 Notice that my groceries array now contains Milk, Eggs, Frosted
Flakes, Salami, and Juice. I just have to reiterate how important the
commas are. Without the commas, you'll just have one giant item
instead. All right, now that you've learned how to declare an array.
Let's look at how you can actually use it to store and work with data.

Accessing Array Values

 One of the nice things about arrays is that you not only have easy
access to the array, but you also have easy access to the array
values...similar to highlighting an item in your grocery list:
 The only thing you need to know is what the procedure is for
accessing an individual item. Inside an array, each item is assigned a
number starting with zero. In the above example, Milk would be
given the value 0, Eggs the value 1, Frosted Flakes the value 2, and
so on. The formal term for these numbers is called the index value.

 Let's say that our groceries array is declared as follows:

var groceries = ["Milk", "Eggs", "Frosted Flakes", "Salami", "Juice"];

If I wanted to access an item from the array, all I need to do is pass in


the index value of the item I am interested in:

groceries[1]
 The index value is passed in to your array using square brackets. In
this example, you are referring to the Eggs value because the index
position 1 refers to it. If you passed in a 2, you would return Frosted
Flakes. You can keep passing in a index value until you have no more
values left.

 The range of numbers you can use as your index values is one less
than your array's length. The reason is that, your index values start
with a value of 0. If your array only has 5 items, trying to display
grocery[6] or grocery[5] will result in a message of undefined.
 Let's go one step further. In most real world scenarios, you will want
to programmatically go through your array as opposed to accessing
each item individually. You can take what I explained in the previous
paragraph and use a for loop to accomplish this:

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

var item = groceries[i];

 Notice the range of your loop starts at 0 and ends just one before
your array's full length (as returned by the length property). This
works because, your array index values go from 0 to one short of the
value returned for the array's length. And yes, the length property
returns a count of all the items in your array!
Adding Items to Your Array
 Rarely will you leave your array in the state you initialized it in
originally. You will want to add items to it. To add items to your array,
you will use the push method:

[Link]("Cookies");

 The push method is called directly on your array, and you pass in the
data you want to add to it. By using the push method, your newly
added data will always find itself at the end of the array.

 For example, after running the code on our initial array, you will see
Cookies added to the end of your groceries array:
 If you want to add data to the beginning of your array, you use the
unshift method:

[Link]("Bananas");

 When data is added to the beginning of your array, the index value
for all of the existing items increases to account for the newly
inserted data:
 The reason is that the first item in your array will always have an
index value of 0. This means that the space originally occupied by the
0th item needs to push itself and everything below it out to make
room for the new data.

 Both the push and unshift methods, besides adding the elements to
the array when you use them, return the new length of the array as
well:

alert([Link]("cookies")); // returns 6

 Not sure why that is useful, but keep it under your hat in case you do
need it.
Removing Items from the Array
 To remove an item from the array, you can use the pop or shift
methods. The pop method removes the last item from the array and
returns it:

var lastItem = [Link]();

 The shift method does the same thing on the opposite end of the
array. Instead of the last item being removed and returned, the shift
method removes and returns the first item from the array:

var firstItem = [Link]();

 When an item is removed from the beginning of the array, the index
positions of all remaining elements is decremented by 1 to fill in the
gap:
 Note that, when you are adding items to your array using unshift or
push, the returned value from that method call is the new length of
your array. That is not what happens when you call the pop and shift
methods, though! When you are removing items using shift and pop,
the value returned by the method call is the removed item itself!
Finding Items in the Array
 To find items inside your array, you have two built-in methods called
indexOf and lastIndexOf. These methods work by scanning your array
and returning the index position of the matching element.

 The indexOf method returns the first occurrence of the item you are
searching for:

var groceries =["milk", "eggs", "frosted flakes", "salami", "juice"];

var resultIndex = [Link]("eggs",0);

alert(resultIndex); // 1
 Notice that the resultIndex variable stores the result of calling
indexOf on our groceries array. To use indexOf, I pass in the element I
am looking for along with the index position to start from:

[Link]("eggs",0);

 The value returned by indexOf in this case will be [Link] lastIndexOf


method is similar to indexOf in how you use it, but it differs a bit on
what it returns when an element is found. Where indexOf finds the
first occurrence of the element you are searching for, lastIndexOf
finds the last occurrence of the element you are searching for and
returns that element's index position. When you search for an
element that does not exist in your array, both indexOf and
lastIndexOf return a value of -1.
Merging Arrays
 Let's say you have two arrays called good and bad:

var good = ["Mario", "Luigi", "Kirby", "Yoshi"];

var bad = ["Bowser", "Koopa Troopa", "Goomba"];

 To combine both of these arrays into one array, use the concat
method on the array you want to make bigger and pass the array you
want to merge into it as the argument. What will get returned is a
new array whose contents are both good and bad:
var goodAndBad = [Link](bad);
trace(goodAndBad);

 In this example, because the concat method returns a new array, the
goodAndBad variable ends up becoming an array that stores the
results of our concatenation operation. The order of the elements
inside goodAndBad is good first and bad second.
Sorting an Array
 The sort() method sorts an array alphabetically:
Example
 var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](); // Sorts the elements of fruits
 Imagine that you wanted to sort an array alphabetically before you
wrote the array to the browser. Well, this code has already been
written and can be accessed by using the Array's sort method.
JavaScript Code:
<script type="text/javascript">
<!–
var myArray2= new Array();
myArray2[0] = "Football";
myArray2[1] = "Baseball";
myArray2[2] = "Cricket";
[Link]();
[Link](myArray2[0] + myArray2[1] + myArray2[2]); //--> </script>
Reversing an Array
 The reverse() method reverses the elements in an array.

 You can use it to sort an array in descending order:

Example

 var fruits = ["Banana", "Orange", "Apple", "Mango"];


[Link](); // Sorts the elements of fruits
[Link](); // Reverses the order of the elements
Array Properties:
Here is a list of each property and their description.
Property Description
Returns a reference to the array function that created
constructor
the object.

The property represents the zero-based index of the


index
match in the string

This property is only present in arrays created by regular


input
expression matches.

length Reflects the number of elements in an array.

The prototype property allows you to add properties and


prototype
methods to an object.
Array Methods
Here is a list of each method and its description.
Method Description
concat() Returns a new array comprised of this array joined with other array(s) and/or value(s).

every() Returns true if every element in this array satisfies the provided testing function.

filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true.
forEach() Calls a function for each element in the array.
indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
join() Joins all elements of an array into a string.
lastIndexOf() Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.

map() Creates a new array with the results of calling a provided function on every element in this array.
pop() Removes the last element from an array and returns that element.
push() Adds one or more elements to the end of an array and returns the new length of the array.

reduce() Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.

reduceRight() Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.

reverse() Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
shift() Removes the first element from an array and returns that element.
slice() Extracts a section of an array and returns a new array.
some() Returns true if at least one element in this array satisfies the provided testing function.
toSource() Represents the source code of an object
sort() Sorts the elements of an array.
splice() Adds and/or removes elements from an array.
toString() Returns a string representing the array and its elements.
unshift() Adds one or more elements to the front of an array and returns the new length of the array.
JavaScript: Form Validation
 Validating form input with JavaScript is easy to do and can save a lot
of unnecessary calls to the server as all processing is handled by the
web browser. It can prevent people from leaving fields blank, from
entering too little or too much or from using invalid characters.

 When form input is important, it should always be verified using a


secure server-side script. Otherwise a browser with JavaScript
disabled, or a hacker trying to compromise your site, can easily
submit invalid data.
1. Restricting input to alphanumeric characters
 In the following example, the single input box, input field, must:

a) not be empty; and

b) contain only alphanumeric characters and spaces. Only if both tests


are passed can the form be submitted (when the script returns a value
of true).
<html> <body> <script type="text/javascript">
function checkForm(form)
{ // validation fails if the input is blank
if([Link] == "") {
alert("Error: Input is empty!");
[Link]();
return false;
} // regular expression to match only alphanumeric characters and
spaces
var re = /^[\w ]+$/; // validation fails if the input doesn't match our regular expression
if(![Link]([Link])) {
alert("Error: Input contains invalid characters!");
[Link]();
return false;
} // validation was successful
return true;
}
</script>
<form method="POST" action="form-handler" onsubmit="return checkForm(this);">
<p>Input: <input type="text" size="32" name="inputfield">
<input type="submit"></p>
</form> </body> </html>
The pre-defined class \w represents any alphanumeric character or the
'_' underscore.

 The regular expression ^[\w ]+$ will fail if the input is empty as it
requires at least one character (because we used + instead of *). The
first test in the example is therefore only necessary in order to
provide a different error message when the input is blank.

 The purpose of a form validation script is to return a boolean value


(true or false) to the onsubmit event handler. A value of true means
that form will be submitted while a false value will block the form
from being submitting. The focus() command is used to set the focus
to the problem element. You can test the above script with different
input values using this form:
 The form is put together as follows:

<form method="POST" action="form-handler" onsubmit="return


checkForm(this);">

<p>Input: <input type="text" size="32" name="inputfield">

<input type="submit"></p> </form>


 The name attribute of the input field is used to reference that field
from within the checkForm function. With the advent of DHTML it's
tempting to use id's to reference form fields, but that can lead to
namespace conflicts and why make things more complicated than
necessary.

 When the form is submitted - either by hitting Enter or clicking on


the Submit button - the onsubmit handler is triggered. This then
calls our checkForm() function, passing a reference to itself (the
form) as the only variable. This makes the value of the input box
available within the function as [Link] (the 'value' of the
field called 'input' belonging to the form).
 Other form values are available using a similar syntax, although this
becomes more complicated if you're using SELECT lists, checkboxes or
radio buttons (see below for examples).

 The checkForm function tests the form input against our conditions,
returning a value of true if the form is to be submitted (when all tests
have been passed) or false to abort (cancel) the form submission. It's
that simple.

 In a real-life situation you will most likely have more fields to check,
and more complicated conditions, but the principle remains the
same. All you need to do is extend the checkForm function to
encompass the new fields and conditions:
<script type="text/javascript">

function checkForm(form) {

if(!condition1) {

alert("Error: error message");

[Link]();

return false;

} if(!condition2) {

alert("Error: error message");

[Link]();

return false;

} ... return true;


} </script>
 When a return command is encountered, execution of the function
is halted. In other words if the first condition fails, the second
condition will not be tested and so forth. Only when all conditions
have been satisfied do we reach the return true command, in which
case the form will be submitted.

 You'll see that the all validation scripts presented on this and
subsequent pages adhere to the same basic format.
2. 2. Working with different types of FORM elements
 Text/Textarea/Password boxes

 The value of a text input box (or a textarea or password input) is


available using the syntax [Link]. This is not the case
for other input types.

[Link]

To check whether two inputs have the same is quite


simple:if([Link] == [Link]) {

// values are identical

}
 Make sure to always use == for comparisons. If you use = (the
assignment operator) instead then it can take a long time to debug.

 and to see if they have different values we just reverse the logic:

if([Link] != [Link]) { // values are different }

 If you want to test numeric values (or add or subtract them) then you
first have to convert them from strings to numbers. By default all
form values are accessed as as strings.

var field1 = parseInt([Link]);

var field2 = parseInt([Link]);

if(field1 > field2) { // field1 as a number is greater than field2 as a


number }
 parseFloat is the same as parseInt except that it also works for
floating point numbers.

Select/Combo/Drop-down boxes

 The value of a SELECT input element is accessed using:

 var selectBox = [Link];

 var selectedValue = [Link][[Link]].value


var selectedText = [Link][[Link]].text

 where fieldname is the SELECT element, which has an array of


options and a value selectedIndex that tells you which option has
been selected. The illustration below shows this relationship:
 Note that the 'I' in selectedIndex needs to be capitalised - JavaScript
functions and variables are always case-sensitive.

 If you define a value for the OPTION elements in your SELECT list,
then .value will return that, while .text will return the text that is
visible in the browser. Here's an example of what this refers to:

<option value="value">text</option>

 If you just want to check that an option has been chosen (ie. that the
SELECT box is no longer in it's default state) then you can use:
if([Link] > 0) {
// an option has been selected
} else { // no option selected }
Checkboxes
These really are simple:
[Link]
will return a boolean value (true or false) indicating
whether the checkbox is in a 'checked' state.
function checkForm(form) {
if([Link]) {

alert("The checkbox IS checked");

} else {

alert("The checkbox IS NOT checked");

} return false;

Radio buttons

Radio buttons are implemented as if they were an array of checkboxes.


To find out which value (if any) has been selected, you need to loop
through the array until you find which one has been selected:
<script type="text/javascript">
function checkRadio(field) {
for(var i=0; i < [Link]; i++) {
if(field[i].checked) return field[i].value;
}
return false;
}
</script>
 The form handler function is then the following:

function checkForm(form) {

if(radioValue = checkRadio([Link])) {

alert("You selected " + radioValue);

return true;

} else {

alert("Error: No value was selected!");

return false;

}
<!DOCTYPE HTML>
<html><head>
<meta charset="UTF-8">
<title>Login</title>
<script type="text/javascript">
function validate(form){
var userName = [Link];
var password = [Link];

if ([Link] === 0) {
alert("You must enter a username.");
return false;
}
if ([Link] === 0) {
alert("You must enter a password.");
return false;
}
return true;
}
</script>
</head>
<body>
<h1>Login Form</h1>
<form method="post" action="[Link]"
onsubmit="return validate(this);">
Username: <input type="text" name="Username" size="10"><br>
Password: <input type="password" name="Password" size="10"><br>
<input type="submit" value="Submit">
<input type="reset" value="Reset Form">
</form></body></html>

You might also like