0% found this document useful (0 votes)
11 views43 pages

JavaScript Client-Side Programming Guide

JavaScript is a client-side scripting language used to enhance interactivity on HTML pages, allowing for dynamic content and user interaction. It has advantages such as saving server traffic and being easy to learn, but also has limitations like security issues and lack of multithreading. The document covers JavaScript syntax, variable declaration, operators, and control structures like loops and conditional statements.

Uploaded by

Punitha Brawin
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)
11 views43 pages

JavaScript Client-Side Programming Guide

JavaScript is a client-side scripting language used to enhance interactivity on HTML pages, allowing for dynamic content and user interaction. It has advantages such as saving server traffic and being easy to learn, but also has limitations like security issues and lack of multithreading. The document covers JavaScript syntax, variable declaration, operators, and control structures like loops and conditional statements.

Uploaded by

Punitha Brawin
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

UNIT-II

CLIENT SIDE PROGRAMMING

2.1 An Introduction to JavaScript

JavaScript is the programming language of HTML and the Web, Also called as Client-Side Scripting
Language designed to add interactivity to HTML pages.
It is a Client-side script to interact with the user and make dynamic pages.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly
because of the excitement being generated by Java.
Features of JavaScript
JavaScript is an open source scripting language.
It is lightweight.
It creates network-centric applications.
It is platform independent.
It validates form data.
It reduces server load.
What can a JavaScript do?
JavaScript can put dynamic text into an HTML page
JavaScript can react to events - A JavaScript can be set to execute when
something happens, like when a page has finished loading or when a user clicks
on an HTML element
JavaScript can read and write HTML elements - A JavaScript can read and
change the content of an HTML element
JavaScript can be used to validate data - A JavaScript can be used to validate form
data before it is submitted to a server. This saves the server from extra processing
JavaScript can be used to create cookies - A JavaScript can be used to store
and retrieve information on the visitor's computer
Advantages of JavaScript
JavaScript saves server traffic.
It performs the operations very fast.
It is simple to learn and implement.
It is versatile.
JavaScript pages are executed on the client side.
JavaScript extends its functionality to the web pages.
Disadvantages of JavaScript
JavaScript cannot be used for networking applications.
It doesn't have any multithreading or multiprocessor capabilities.
It has security issues being a client-side scripting language.
What is a script?
Script is a small, embedded program.
The most popular scripting languages on the web are, JavaScript orVBScript.
HTML does not have scripting capability, you need to use <script> tag.
The <script> tag is used to generate a script.
The </script> tag indicates the end of the script or program.
1
Example : Type attribute
<script type = “text/javascript”> [Link](“TutorialRide”);
</script>
The 'type' attribute indicates which script language you are using withthe type
attribute.
Example : Language attribute
<script language= “javascript”> [Link](“TutorialRide”);
</script>
 You can also specify the <script language> using the 'language'
attribute.
Types of Scripts
1. Client-Side Scripting
2. Server-Side Scripting
Client-Side Scripting
 Client-Side Scripting is an important part of the Dynamic HTML(DHTML).
 JavaScript is the main client-side scripting language for the web.
 The scripts are interpreted by the browser.
 Client-Side scripting is used to make changes in the web page afterthey arrive at
the browser.
 It is useful for making the pages a bit more interesting and user-friendly.

Operation of Client-Side Scripting

In the above diagram,


 The user requests a web page from the server.
 The server finds the page and sends it to the user.
 The page is displayed on the browser with any scripts running duringor after
the display.
 Client-Side scripting is used to make web page changes after theyarrive at the
browser.
 These scripts rely on the user's computer. If the computer is slow,then they may
run slow.
 These scripts may not run at all if the browser does not understandthe
scripting language.
Server-Side Scripting
 Server-Side Scripting is used in web development.
 The server-side environment runs a scripting language which is calleda web
server.

2
 Server-Side Scripting is used to provide interactive web sites.
 It is different from Client-Side Scripting where the scripts are run by viewing the web browser,
usually in JavaScript.
 It is used for allowing the users to have individual accounts andproviding data
from databases.
 It allows a level of privacy, personalization and provision of
information that is very useful.
 It includes [Link] and PHP.
 It does not rely on the user having specific browser or plug-in.
 It is affected by the processing speed of the host server.

Operation of Server-Side Scripting

In the above diagram,


 The client requests a web page from the server.
 The script in the page is interpreted by the server, creating or changing the page
content to suit the user (client) and the passing data around.
 The page in its final form is sent to the user(client) and then cannot bechanged
using Server-Side Scripting.
 Server-Side Scripting tends to be used for allowing the users to have individual
accounts and provides data from the databases.
 These scripts are never seen by the user.
 Server-Side script runs on the server and generate results which are sent to the
user.
Syntax to write JavaScript
In HTML, JavaScript code is inserted between <script> and </script>tags.
<script> tag alerts the browser program to start interpreting all the textbetween
these tags as a script (program statements).
Old JavaScript examples may use a type attribute: <script
type="text/javascript">
The type attribute is not required. JavaScript is the default scriptinglanguage in
HTML.
Example: Displaying the string ―Hello World!‖ on the browser window:
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!-- [Link]("Hello World!") //-->
</script>
</body></html>
3
[Link] writes a
string into our HTML

Ways to write/execute JavaScript: (Where to write? JavaScript in <head> or <body>??)


You can place any number of scripts in an HTML document. Scripts can be
placed in the <body>, or in the <head> section of an HTML page, or in both.
There are three ways of executing JavaScript on a web browser.
1) Inside <HEAD> tag
2) Within <BODY> tag
3) In an External File

 Scripts can also be placed in external files:


o External scripts are practical when the same code is used in many different
webpages.
o JavaScript files have the file extension .js.
o To use an external script, put the name of the script file in the src (source)
attributeof a <script> tag.
o Example: <script src="[Link]"></script>
o
External scripts cannot contain <script> tags.

4
Rules for writing the JavaScript code:
 Script should be placed inside the <script> tag.
 A semicolon at the end of each statement is optional.
 The single line comment is just two slashes (//) and multiple linecomment starts
with /* and ends with */. 
 Use '[Link]' for writing a string into HTML document.
 JavaScript is case sensitive.
 You can insert special characters with backslash (\& or \$).
Displaying Output in JavaScript
 JavaScript Display Possibilities : JavaScript can "display" data indifferent
ways:
o Writing into an HTML element, using innerHTML.
o Writing into the HTML output using [Link]().
o Writing into an alert box, using [Link]().
o Writing into the browser console, using [Link]().
Example:
<html>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = 5 + 6;
[Link](10 + 10)
[Link](10 + 30);
[Link](10 + 40);
</script>
</body>
</html>
Alert Box
 An alert box is often used if you want to make sure information comesthrough
to the user.
 When an alert box pops up, the user will have to click "OK" toproceed.
 Syntax; [Link]("sometext");

5
Confirm Box
 A confirm box is often used if you want the user to verify or acceptsomething.
 When a confirm box pops up, the user will have to click either "OK" or"Cancel"
to proceed.
 If the user clicks "OK", the box returns true. If the user clicks"Cancel", the
box returns false.
 Syntax: [Link]("sometext");

Prompt Box
 A prompt box is often used if you want the user to input a valuebefore entering
a page.
 When a prompt box pops up, the user will have to click either "OK" or"Cancel"
to proceed after entering an input value.
 If the user clicks "OK" the box returns the input value. If the userclicks
"Cancel" the box returns null.
 Syntax: [Link]("sometext","defaultText");

2.1.4: JavaScript Variables

 Variables are declared with the var keyword


 JavaScript variable can hold a value of any data type or expressions.
 A variable can have a short name, like x, or a more descriptive name, like carname.
Rules for JavaScript variable names:
 Variable names are case sensitive (y and Y are two different variables)
 Variable names must begin with a letter or the underscore character.
 Because JavaScript is case-sensitive,variable names are case-sensitive.
6
Declaring (Creating) JavaScript Variables
Creating variables in JavaScript is most often referred to as "declaring"variables. You
can declare JavaScript variables with the var keyword:
var x;
var carname;
After the declaration shown above, the variables are empty (they have no values yet).
However, you can also assign values to the variables when you declare them:
var x=5;
var carname="Volvo";
After the execution of the statements above, the variable x will hold thevalue 5,
and carname will hold the value Volvo.

Assigning Values to Undeclared JavaScript Variables


If you assign values to variables that have not yet been declared, thevariables will
automatically be declared. These statements:
x=5;
carname="Volvo"; have the same effect as:
var x=5;
var carname="Volvo";
Redeclaring JavaScript Variables
If you redeclare a JavaScript variable, it will not lose its original value. varx=5;
var x;
After the execution of the statements above, the variable x will still have thevalue of 5.
The value of x is not reset (or cleared) when you redeclare it.
The Lifetime of JavaScript Variables
 If you declare a variable within a function, the variable can only be accessed within
that function. When you exit the function, the variable is destroyed. These
variables are called local variables.
 If you declare a variable outside a function, all the functions on your page can
access it. These variables are called global variables. The lifetime of these variables
starts when they are declared, and ends when the page is closed. 
JavaScript Operators
Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Reminder)
7
++ Increment
-- Decrement
Comparison Operators
Operator Description
== Equal To
=== Exactly Equal To
!= Not Equal To
< Less Than
> Greater Than
<= Less Than or Equal To
>= Greater Than or Equal To
Assignment Operators
Operator Description
= Simple Assignment
+= Add and Assignment
-= Subtract and Assignment
*= Multiply and Assignment
/= Divide and Assignment
%= Modulus and Assignment
Logical Operators
Operator Description
&& Logical AND
|| Logical OR
! Logical NOT
Bitwise Operators
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
˜ Bitwise NOT
<< Left Shift
>> Right Shift
>>> Right Shift with Zero
Special Operators
Operator Description
NEW Creates an instance of an object type.
DELETE Deletes property of an object.
DOT(.) Specifies the property or method.
VOID Does not return any value. Used to return a URL with no value.
JavaScript Control and Looping Structure
1) If Statement
 IF statement is a conditional branching statement.
 In 'IF' statement, if the condition is true a group of statement is [Link] if the
condition is false, the following statement is skipped.
if(condition)
8
{
//Statement 1;
//Statement 2;
}
Example : Simple Program for IF Statement
<html>
<body>
<script type="text/javascript">
var num = prompt("Enter Number");if
(num > 0)
{
alert("Given number is Positive!!!");
}
</script>
</body>
</html>
Output:

2) If – Else Statement
 If – Else is a two-way decision statement.
 It is used to make decisions and execute statements conditional
Flow Diagram of If – Else Statement

<html>
<head>
<script type="text/javascript">
var no = prompt("Enter a Number to find Odd or Even");no =
parseInt(no);
if (isNaN(no))
9
{
alert("Please Enter a Number");
}
else if (no == 0)
{
alert("The Number is Zero");
}
else if (no % 2)
{
alert("The Number is Odd");
}
else
{
alert("The Number is Even");
}
</script>
</head>
</html>

Output

3) Switch Statement
 Switch is used to perform different actions on different conditions.
 It is used to compare the same expression to several different values.
Flow Diagram of Switch Statement

10
Example : Simple Program for Switch Statement
<html>
<head>
<script type="text/javascript">
var day = prompt("Enter a number between 1 and 7");switch
(day)
{
case (day="1"):
[Link]("Sunday");
break;
case (day="2"):
[Link]("Monday");
break;
case (day="3"):
[Link]("Tuesday");
break;
case (day="4"):
[Link]("Wednesday"); break;
case (day="5"):
[Link]("Thursday");break;
case (day="6"):
[Link]("Friday"); break;
case (day="7"):
[Link]("Saturday");break;
default:
[Link]("Invalid Weekday");
break;
}
</script>
</head>
</html>
Output:

4) For Loop
 For loop is a compact form of looping.
It includes three important parts:
1. Loop Initialization
2. Test Condition
3. Iteration
11
 All these three parts come in a single line separated by semicolons(;).
Flow Diagram of 'For' Loop

Example : Palindrome Program using For Loop


<html>
<body>
<script type="text/javascript">
function palindrome()
{
var revstr = " ";
var strr = [Link]("strr").value;var i =
[Link];
for(var j=i; j>=0; j--)
{
revstr = revstr+[Link](j);
}
if(strr == revstr)
{
alert(strr+" - is Palindrome");
}
else
{
alert(strr+" - is not a Palindrome");
}
}
</script>
<form>
Enter a String or Number: <input type="text" id="strr"name="checkpalindrome"><br>
<input type="submit" value="Check" onclick="palindrome();">
</form>
</body>
</html>
Output:

12
5) For-in Loop
 For-in loop is used to traverse all the properties of an object.
 It is designed for looping through arrays.
Syntax
for (variable_name in Object)
{
//Statements;
}
6) While Loop
 While loop is an entry-controlled loop statement.
 It is the most basic loop in JavaScript.
 It executes a statement repeatedly as long as expression is true.
 Once the expression becomes false, the loop terminates.

Flow Diagram of While Loop


Example : Fibonacci Series Program using While Loop
<html>
<body>
<script type="text/javascript">var
no1=0,no2=1,no3=0;
[Link]("Fibonacci Series:"+"<br>");while
(no2<=10)
{
no3 = no1+no2;
no1 = no2;
no2 = no3;
[Link](no3+"<br>");
}
</script>
</body>
</html>
7) Do-While Loop
 Do-While loop is an exit-controlled loop statement.
 Similar to the While loop, the only difference is condition will be checked atthe end of
13
the loop.
 The loop is executed at least once, even if the condition is false.

Flow Diagram of Do – While


Example : Simple Program on Do-While Loop
<html>
<body>
<script type ="text/javascript">

var i = 0;
do
{
[Link](i+"<br>") i++;
}
while (i <= 5)
</script>
</body>
</html>
Output:
0
1
2
3
4
5
Difference between While Loop and Do – While Loop
While Loop Do – While Loop
In while loop, first it checks the In Do – While loop, first it executes the
condition and then executes the program and then checks the condition.
program.
It is an entry – controlled loop. It is an exit – controlled loop.
The condition will come before the The condition will come after the body.
body.
If the condition is false, then it It runs at least once, even though the
14
terminates the loop. conditional is false.
It is a counter-controlled loop. It is a iterative control loop.
8) Break Statement
 Break statement is used to jump out of a loop.

 It is used to exit a loop early, breaking out of the enclosing curly braces.
Flow Diagram of Break Statement

9) Continue Statement
 Continue statement causes the loop to continue with the next iteration.
 It skips the remaining code block.
Flow Diagram of Continue Statement

Syntax

do
{
//Statements;
}

2.1.3: JavaScript Functions


A JavaScript function is a block of code designed to perform a particulartask.
A JavaScript function is executed when "something" invokes it (calls it).

15
JavaScript Built-in Functions
JavaScript provides number of built-in functions.
Common Built-in Functions
Functions Description
isNan() Returns true, if the object is Not a Number.
Returns false, if the object is a number.
parseFloat If the string begins with a number, the function reads throughthe string
(string) until it finds the end of the number; cuts off the remainder of the string and
returns the result.
If the string does not begin with a number, the function returnsNaN.
parseInt If the string begins with an integer, the function reads throughthe string
(string) until it finds the end of the integer, cuts off the remainder of the string and
returns the result.
If the string does not begin with an integer, the function returnsNaN (Not
a Number).
String Converts the object into a string.
(object)
eval() Returns the result of evaluating an arithmetic expression.
User-defined Functions
User-defined function means you can create a function for your own use. Youcan
create yourself according to your need.
In JavaScript, these functions are written in between the <HEAD> tag of the
HTML page.
JavaScript Function Syntax
 function keyword --- followed by a name ---- followed by parentheses().
 Function names can contain letters, digits, underscores, and dollarsigns
 (same rules as variables).
 The parentheses may include parameter names separated by commas:
 (parameter1, parameter2, ...)
 The code to be executed, by the function, is placed inside curlybrackets: {}
 Syntax:
function name(parameter1, parameter2, parameter3)
{
// code to be executed
}
Example :
function myFunction(p1, p2)
{
return p1 * p2; // The function returns the product of p1 and p2
}
Function Invocation
 The code inside the function will execute when "something" invokes(calls) the
function:
 When an event occurs (when a user clicks a button)
 When it is invoked (called) from JavaScript code
16
 Automatically (self invoked)
Function Return
 When JavaScript reaches a return statement, the function will stopexecuting.
 If the function was invoked from a statement, JavaScript will "return"to
execute the code after the invoking statement.
 Functions often compute a return value. The return value is "returned"back to the
"caller―.
Example:

Example:
<html>
<head>
<script>
function toCelsius(f) { var
res=(5/9) * (f-32);
[Link](f+ " Degree Fahrenheit is = "+[Link](res,2)+" Degree Celsius");
}
</script>
</head>
<body>
<h2>JavaScript Functions</h2>
<button onclick='toCelsius(98);'>Click Here</button>
</body>
</html>

2.1.3: JavaScript Arrays


Array is a grouping of objects.
It stores multiple values in a single variable.
It stores a fixed-size sequential collection of elements of the same type.
It is used to store collection of data.
Creating and Initializing Arrays
var variable_name = new Array(); // Creating an Array
17
vararr = []; // Creating an Array
var arr1 = [1, 2, 3]; // Initializing an Array
Array Properties
Array
Properties Description
Constructor It returns a reference to the array function that created theobject.
Index It represents the zero-based index of the match in thestring.
Length It reflects the number of elements in an array.
Input It presents only an array created by regular expressionmatches.
Prototype It allows you to add properties and methods to an object.
Array Methods
Methods Description
concat() It returns a new array comprised of this array joined with otherarrays and
values.
every() It returns true if every element in this array satisfies the providedtesting
function.
filter() It creates a new array with all the elements of this array for whichthe
provided filtering function returns true.
indexOf() It returns the first index of an element within the array equal tothe
specified value.
join() It joins all elements of an array into a string.
pop() It removes the last element from an array and returns thatelement.
push() It adds one or more elements to the end of an array and returnsthe new
length of the array.
reverse() It reverses the order of the elements of an array.
sort() It represents the source code of an object.
Example: Program on Array Methods – POP() & PUSH()
<html>
<body>
<button onclick="arrpop();">POP</button>
<button onclick="arrpush();"> PUSH </button>
<script>
function arrpop()
{
var numbers = ["1", "2", "3", "4", "5", "ABC"];
[Link]([Link]()+" "+"Removed"+"<br>");
//pop() removes the last element of an array
// Now we have [1,2,3,4,5]
[Link]("Now length is: "+[Link]); // ABC removed
}
function arrpush()
{
var numbers = ["1","2","3","4","5","6"]
[Link]("7");
// now we got ["1","2","3","4","5","6"]
18
[Link]("Added element is :"+" "+numbers[[Link]-1])
// Now we have [1,2,3,4,5,6]
[Link]("<br>"+"Now length is: "+[Link]); // 7 Added
}
</script>
</body>
</html>
Output:

2.2 DOM MODEL (May / June 2011, May /June 2012)


Definition: DOM
The W3C Document Object Model (DOM) is a platform and language- neutral
interface that allows programs and scripts to dynamically access and update the
content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
 Core DOM - standard model for all document types
 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents
Various DOM Levels:
DOM 0 – supported by early browsers. This could support JavaScript. DOM 1 –
released in 1998 which was focused on XHTML and HTML. DOM 2 – Released
in 2000. Supports stylesheets, event model andtraversal within the documents.
DOM 3 – Current release published in 2004. It could deal with XMLwith
DTD and schema, document validations.
The DOM Tree:
In DOM, when the HTML or XML document’s elements are syntactically
correct, the documents are represented as tree structure in which every element is
represented as nodes. This tree structure is called as DOM Tree.
The HTML DOM model is constructed as a tree of Objects:
<html>
<head> <head>
<title>My Page</title>
</head> <body>
<body>
<title> <
<h1> Hello! </h1>
</body>

</html>

At the top level, there is an html node, with two children: head andbody, among which only head
has a child tag title.
 HTML tags are element nodes in DOM tree, pieces of text become textnodes.
Both of them are nodes, just the type is different.
19
ACCESSING DOM:
 The HTML DOM can be accessed with JavaScript (and with otherprogramming
languages).
 In the DOM, all HTML elements are defined as objects.
 With the object model, JavaScript gets all the power it needs to createdynamic
HTML:
JavaScript can change all the HTML elements in the page
JavaScript can change all the HTML attributes in the page
JavaScript can change all the CSS styles in the page
JavaScript can remove existing HTML elements and attributes
JavaScript can add new HTML elements and attributes
JavaScript can react to all existing HTML events in the page
JavaScript can create new HTML events in the page
Types of nodes
There are many types of nodes in the DOM document tree that specifies what kind of
node it is. Every Object in the DOM document tree has properties and methods defined
by the Node host object.
The following table lists the non method properties of Node object.

The following table lists the node types commonly encountered in HTMLdocuments and
the nodeType value for each one.

Node Type nodeType constant nodeType


value
Element Node.ELEMENT_NODE 1
Text Node.TEXT_NODE 3
Document Node.DOCUMENT_NODE 9
Comment Node.COMMENT_NODE 8
DocumentFragment Node.DOCUMENT_FRAGMENT_NODE 11
Attr Node.ATTRIBUTE_NODE 2

20
The following table lists the method properties of Node object.

The HTML DOM Document:


In the HTML DOM object model, the document object represents our webpage.
The document object is the owner of all other objects in our web page.
Finding HTML Elements:
Often, with JavaScript, we may want to manipulate HTML elements.
To do so, we have to find the elements first. There are a three of ways to dothis:
Finding HTML elements by id
Finding HTML elements by tag name
Finding HTML elements by class name
Method Description
[Link]() Find an element by element id
[Link]() Find elements by tag name
[Link]() Find elements by class name
Changing HTML Elements
Method Description
[Link]= Change the inner HTML of an element
Change the attribute of an HTML
[Link]= element
Change the attribute of an HTML
[Link](attribute,value) element
[Link]= Change the style of an HTML element

Changing the Value of an Attribute:


To change the value of an HTML attribute, use this syntax:
[Link](id).attribute=new value
Adding and Deleting Elements
Method Description
[Link]() Create an HTML element
[Link]() Remove an HTML element
[Link]() Add an HTML element
[Link]() Replace an HTML element

21
[Link](text) Write into the HTML output stream
Adding Events Handlers
Method Description
Adding event handler
[Link](id).onclick=function(){code} code to an onclick event
Reacting to Events
 A JavaScript can be executed when an event occurs, like when a userclicks on
an HTML element.
 To execute code when a user clicks on an element, add JavaScriptcode to
an HTML event attribute:
onclick=JavaScript
Examples of HTML events:
When a user clicks the mouse
When a web page has loaded
When an image has been loaded
When the mouse moves over an element
Example:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">var
page_element=""; function end()
{
var txt=[Link]("end of document");[Link](txt);
}
function Display() // function definition
{
for(i=0;i<[Link];i++)
{
page_element+="<br>"+[Link][i].tagName; // accessing all the
elements using DOM
}
[Link]="center"; // accessing element's atrribute
[Link]+=page_element;// setting the element's text
}
</script>
</head>
<body onload="Display()">
<p class="exp">Example for Accessing Elements</p>
<div id="main">
<p>The DOM is very useful.</p>
<p id="demo"></p>
</div>
<p class="exp">Thank You</p>
<script>
var x = [Link]("main");var y =
[Link]("p"); y[1].innerHTML =
"Welcome DOM";

22
var z=[Link]("exp");
z[0].[Link]="blue";
z[1].[Link]="Green";
</script>
<p id="pmsg" > <strong> Various Elements used in this web documentsare:</strong></p>
<button id="btn" value="click me" onClick="end()">Click Me</button>
</body></html>

What is form validation?


 Form validation is the process of checking the forms that have beenfilled in
correctly before they are processed.
 It provides a method to check the user entered information on client-sidebefore the
data is submitted to the server-side.
 It includes two methods for validating forms:
1. Server-Side (ASP, PHP)
2. Client-Side (JavaScript)
 It displays alerts for incorrect data entered by the user.
 Client-side validation is faster than Server-side validation.
Example : Simple Form Validation Program
[Link] //File name
<html>
<body>
<script>
function validateemail()
{
var a = [Link];var
atposition = [Link]("@");
var dotposition = [Link](".");
if (atposition<1 || dotposition<atposition+2 ||
dotposition+2>=[Link])
{
alert("Please Enter a valid E-mail Id");
return false;
23
}
}
</script>
</body>
<body>
<form name="myform" method="post" action="[Link]"onsubmit="return
validateemail();">
Enter Your Email Id: <input type="text" name="email"><br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
[Link] //File name
<html>
<body>
<script type="text/javascript">
alert("You are a Valid User !!!");
</script>
</body>
</html>
Output:

Example 2: Form Validation


<!DOCTYPE html >
<html>
<head>
<title> Registration Form l</title>
<!-- Meta Tags -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- JavaScript -->
<script type="text/javascript">
var ck_name = /^[A-Za-z0-9 ]{3,20}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-
z]{2,6}(?:\.[a-z]{2})?)$/i
var ck_username = /^[A-Za-z0-9_]{1,20}$/;
var ck_password = /^[A-Za-z0-9!@#$%^&*()_]{6,20}$/;

function validate(){
var name = [Link];var
email = [Link];
var username = [Link];var
24
password = [Link];var
gender = [Link];
var errors = [];
if (!ck_name.test(name)) {
errors[[Link]] = "Enter your valid Name ."; }
if (!ck_email.test(email)) {
errors[[Link]] = "You must enter a valid email address.";
}
if (!ck_username.test(username)) {
errors[[Link]] = "You must enter valid UserName with no specialchar .";
}
if (!ck_password.test(password)) {
errors[[Link]] = "You must enter a valid Password min 6 char.";
}
if (gender==0) {
errors[[Link]] = "Select Gender";
}
if ([Link] > 0) {
reportErrors(errors); return
false;
}
return true;
}
function reportErrors(errors){
var msg = "Please Enter Valide Data...\n";for (var
i = 0; i<[Link]; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
</head>
<body>
<center> REGISTRATION FORM</center> <hr>
<form action="[Link]" name="form">
<label> Full Name </label>
<input type="text" name="name" value="" /> <br><br>
<label> Email Id </label>
<input type="text" name="email" value="" /> <br><br>
<label> Username </label>
<input type="text" name="username" value="" /> <br><br>
<label> Password </label>
<input type="text" name="password" value="" /> <br><br>
<label> Gender </label>
<select name="gender">
<option value="0">Gender</option>
<option value="1">Female</option>
<option value="2">Male</option>
</select> <br><br>
25
<input type="submit" value="Submit" onclick="return validate()">
</form>
</body>
</html>

Events: An event is an activity that represents a change in the environment. JavaScript


events allow scripts to respond to user interactions and modify the page accordingly.
Example for events: mouse clicks, pressing a key.
Event Handlers: Functions that handle events are called event handlers.
They contain the script that gets executed in response to the events.
Advantage of Event Handling: Events and Event Handler makes web applications
more responsive, dynamic and interactive.
onError Image A JavaScript error occurs.
onFocus Button, Checkbox, The object in question gains focus (e.g.
Password, Radio, by clicking on it orpressing the TAB
Reset, Select, key).
Submit,
Text, TextArea
onKeyDown Image, Link, TextArea The user presses a key.
onKeyPress Image, Link, TextArea The user presses or holds down a key.
onKeyUp Image, Link, TextArea The user releases a key.
onLoad Image, Window The whole page has finished loading.
onMouseDown Button, Link The user presses a mouse button.
onMouseMove None The user moves the mouse.
The user moves the mouse awayfrom the
onMouseOut Image, Link object.
onMouseOver Image, Link The user moves the mouse over
the object.
onMouseUp Button, Link The user releases a mouse button.
26
onMove Window The user moves the browser window or
frame.
onReset Form The user clicks the form's Reset button.
onResize Window The user resizes the browser window or
frame.
onSelect Text, Textarea The user selects text within the field.
onSubmit Form The user clicks the form's Submit button.
onUnload Window The user leaves the page.
List of Events (Intrinsic Event Attributes):
Intrinsic Event Attributes: Intrinsic Event Attribute is an attribute associated with a
HTML element along with an event and the javascript function (Event Handler) to
handle the event.

Event Applies to: Triggered when:


handler
onAbort Image The loading of the image is cancelled.
onBlur Button, Checkbox, The object in question loses focus
Password, Radio, Reset, (e.g. by clicking outside itor
Select, Submit,Text, pressing the TAB key).
TextArea,
Window
onChange Select, Text, TextArea The data in the form element is
changed by the user.
onClick Button, Checkbox,Link, The object is clicked on.
Radio, Reset, Submit
onDblClick Document, Link The object is double-clicked on.
Registering Event Handler:
Assigning an event handler to an event on a DOM node is called
registering an event handler.
Two ways of registration:
1. Inline model: Treating events as attributes of HTML elements. These event
attributes are
called as intrinsic event attributes.
Example: <p onclick=‖myfunction()‖>
Where,
Onclick – intrinsic event attribute.
Myfunction() – event handler to handle the event.
2. Traditional Model: Registering event handler through DOM.
Example:
<!DOCTYPE html>
<html>
<head>
<title> Event Handling in JavaScript</title>
27
<script type="text/javascript">function
handleSubmit()
{
[Link]("Data Successfully submitted!");
}
function handleReset()
{
[Link]("Clearing Form Data ! ............. ");
}
function registerEvent()
{
var reset=[Link]("clear");
[Link]=handleReset;
}
</script>
</head>
<body onload="[Link]('Welcome! opening your page');
registerEvent()">
<form onsubmit="handleSubmit();">
<input type="text" onselect="[Link]('text selected')" /><br />
<input type="submit" value="submit data" /><br />
<input type="reset" id="clear" value="Clear data" /><br />
</form>
</body>
</html>

Javascript | Error and Exceptional Handling


An error is an action which is inaccurate or [Link] are
three types of error in programming
1. Syntax error
2. Logical error
3. Runtime error
Syntax error:
Syntax errors, also called parsing errors, occur at compile time in
traditional programming languages and at interpret time in JavaScript.
For example, the following line causes a syntax error because it is missinga closing
28
parenthesis.
<script type = "text/javascript">
<!--
[Link](;
//-->
</script>
Logical error:
Logic errors can be the most difficult type of errors to track down. These errors are not
the result of a syntax or runtime error. Instead, they occur when you make a mistake in
the logic that drives your script and you do not get the result you expected.
Runtime Error:
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).
For example, the following line causes a runtime error because here the syntax is
correct, but at runtime, it is trying to call a method that does not exist.
<script type = "text/javascript">
<!--
[Link]();
//-->
</script>
What is an Exception?
An exception signifies the presence of an abnormal condition which requires special
operable techniques.
In programming terms, an exception is the anomalous code that breaks the
normal flow of the code. Such exceptions require specialized programming
constructs for its execution.
What is Exception Handling?
In programming, exception handling is a process or method used for handling the
abnormal statements in the code and executing them.
It also enables to handle the flow control of the code/program.
For handling the code, various handlers are used that process the exception and
execute the code.
For example, the Division of a non-zero value with zero will result into infinity
always, and it is an exception. Thus, with the help of exception handling, it can be
executed and handled.
Error Object
When a runtime error occurs, it creates and throws an Error object. Such an object
can be used as a base for the user-defined exceptions too. An error object has two
properties:
1. name: This is an object property that sets or returns an error name.
2. message: This property returns an error message in the string form.
Although Error is a generic constructor, there are following standard built- in error
types or error constructors beside it
1. EvalError: It creates an instance for the error that occurred in theeval(),
which is a global function used for evaluating the js string code.
2. InternalError: It creates an instance when the js engine throws aninternal error.
3. RangeError: It creates an instance for the error that occurs when anumeric
variable or parameter is out of its valid range.
29
4. ReferenceError: It creates an instance for the error that occurs whenan invalid
reference is de-referenced.
5. SyntaxError: An instance is created for the syntax error that mayoccur while
parsing the eval().
6. TypeError: When a variable is not a valid type, an instance is createdfor such
an error.
7. URIError: An instance is created for the error that occurs wheninvalid
parameters are passed in encodeURI() or decodeURI().
The try...catch...finally Statement
The latest versions of JavaScript added exception handling capabilities. JavaScript
implements the try...catch...finally construct as well as the throw operator to
handle exceptions.
 The try statement lets you test a block of code for errors.
 The catch statement lets you handle the error.
 The throw statement lets you create custom errors.
 The finally statement lets you execute code, after try and catch,
regardless of the result.
You can catch programmer-generated and runtime exceptions, but you
cannot catch JavaScript syntax errors.
Here is the try...catch...finally block syntax −
The try block must be followed by either exactly one catch block orone finally
block (or one of both). When an exception occurs in the try block, the
exception is placed in e and the catch block is executed. The optional finally block
executes unconditionally after try/catch.
Example 1:
<!DOCTYPE html>
<html>
<body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>
<script>
function myFunction() {var
message, x;
message = [Link]("p01");[Link] = "";
x = [Link]("demo").value;try {
if(x == "") throw "is empty"; if(isNaN(x))
throw "is not a number";x = Number(x);
if(x > 10) throw "is too high";
if(x < 5) throw "is too low";
}
catch(err) {
[Link] = "Input " + err;
}
finally { [Link]("demo").value
= "";
}
}
30
</script >
</body>
</html>

2.5 VALIDATION-BUILT-IN OBJECTS


Built-in objects are not related to any Window or DOM object model.
These objects are used for simple data processing in the JavaScript.
Some of the built-in objects available in JavaScript are:
1) Date
2) Math
3) String, Number, Boolean
4) RegExp
5) window (Global Obejct)
Math Object
Math object is a built-in static object.
It is used for performing complex math operations.
Math Properties
Math Property Description
SQRT2 Returns square root of 2.
PI Returns Π value.
E\ Returns Euler's Constant.
LN2 Returns natural logarithm of 2.
LN10 Returns natural logarithm of 10.
LOG2E Returns base 2 logarithm of E.
LOG10E Returns 10 logarithm of E.
Math Methods
Methods Description
abs() Returns the absolute value of a number.
acos() Returns the arccosine (in radians) of a number.
ceil() Returns the smallest integer greater than or equal to a number.
cos() Returns cosine of a number.
floor() Returns the largest integer less than or equal to a number.

31
log() Returns the natural logarithm (base E) of a number.
max() Returns the largest of zero or more numbers.
min() Returns the smallest of zero or more numbers.
pow() Returns base to the exponent power, that is base exponent.
Example: Simple Program on Math Object Methods
<html>
<head>
<title>JavaScript Math Object Methods</title>
</head>
<body>
<script type="text/javascript">
var value = [Link](20);
[Link]("ABS Test Value : " + value +"<br>");
var value = [Link](-1);
[Link]("ACOS Test Value : " + value +"<br>");
var value = [Link](1);
[Link]("ASIN Test Value : " + value +"<br>");
var value = [Link](.5);
[Link]("ATAN Test Value : " + value +"<br>");
</script>
</body>
</html>
Output
ABS Test Value : 20
ACOS Test Value : 3.141592653589793
ASIN Test Value : 1.5707963267948966
ATAN Test Value : 0.4636476090008061
2) Date Object
Date is a data type.
Date object manipulates date and time.
Date() constructor takes no arguments.
Date object allows you to get and set the year, month, day, hour,minute, second
and millisecond fields.
Syntax: var variable_name = new Date();
Example: var current_date = new Date();
Date Methods
Methods Description
Date() Returns current date and time.
getDate() Returns the day of the month.
getDay() Returns the day of the week.
getFullYear() Returns the year.
getHours() Returns the hour.
getMinutes() Returns the minutes.
getSeconds() Returns the seconds.
getMilliseconds() Returns the milliseconds.
getTime() Returns the number of milliseconds since January 1,1970 at 12:00
AM.
32
getTimezoneOffset() Returns the timezone offset in minutes for the currentlocale.
getMonth() Returns the month.
setDate() Sets the day of the month.
setFullYear() Sets the full year.
setHours() Sets the hours.
setMinutes() Sets the minutes.
setSeconds() Sets the seconds.
setMilliseconds() Sets the milliseconds.
setTime() Sets the number of milliseconds since January 1, 1970at 12:00 AM.
setMonth() Sets the month.
toDateString() Returns the date portion of the Date as a human- readable string.
toLocaleString() Returns the Date object as a string.
toGMTString() Returns the Date object as a string in GMT timezone.
valueOf() Returns the primitive value of a Date object.
Example : JavaScript Date() Methods Program
<html>
<body>
<center>
<h2>Date Methods</h2>
<script type="text/javascript">var d
= new Date();
[Link]("<b>Locale String:</b> " +[Link]()+"<br>");
[Link]("<b>Hours:</b> " + [Link]()+"<br>");
[Link]("<b>Day:</b> " + [Link]()+"<br>");
[Link]("<b>Month:</b> " + [Link]()+"<br>");
[Link]("<b>FullYear:</b> " + [Link]()+"<br>");
[Link]("<b>Minutes:</b> " + [Link]()+"<br>");
</script>
</center>
</body>
</html>
Output:

String Object
String objects are used to work with text.
It works with a series of characters.
Syntax: var variable_name = new String(string);
Example:
var s = new String(string);

33
String Properties
Properties Description
length It returns the length of the string.
prototype It allows you to add properties and methods to an object.
constructor It returns the reference to the String function that created theobject.
String Methods
Methods Description
charAt() It returns the character at the specified index.
charCodeAt() It returns the ASCII code of the character at the specifiedposition.
concat() It combines the text of two strings and returns a new string.
indexOf() It returns the index within the calling String object.
match() It is used to match a regular expression against a string.
replace() It is used to replace the matched substring with a newsubstring.
search() It executes the search for a match between a regularexpression.
slice() It extracts a session of a string and returns a new string.
split() It splits a string object into an array of strings by separatingthe
string into the substrings.
toLowerCase() It returns the calling string value converted lower case.
toUpperCase() Returns the calling string value converted to uppercase.
Example : JavaScript String() Methods Program
<html>
<body>
<center>
<script type="text/javascript"> var
str = "CareerRide Info"; var s =
[Link]();
[Link]("<b>Char At:</b> " + [Link](1)+"<br>");
[Link]("<b>CharCode At:</b> " +
[Link](2)+"<br>");
[Link]("<b>Index of:</b> " + [Link]("ide")+"<br>");
[Link]("<b>Lower Case:</b> " +
[Link]()+"<br>");
[Link]("<b>Upper Case:</b> " +
[Link]()+"<br>");
</script>
<center>
</body>
</html>

Output:

Boolean Object
The Boolean object is used to convert a non-Boolean value to aBoolean value
(true or false).

34
Syntax
Use the following syntax to create a boolean [Link] val =
new Boolean(value);
Boolean Object Methods
Method Description
toString() Converts a Boolean value to a string, and returns the result
valueOf() Returns the primitive value of a Boolean object
Number Object
The Number object is an object wrapper for primitive numeric [Link]
objects are created with new Number().
Syntax :var num = new Number(value);
Properties of Number object
 Constructor - Returns the function that created the Number object.
 MAX VALUE - Returns maximum numerical value possible in
JavaScript.
 MIN VALUE - Returns minimum numerical value possible in
JavaScript.
 NEGATIVE INFINITY - Represent the value of negative infinity.
 POSITIVE INFINITY - Represent the value of infinity.
 Prototype - Add properties and methods to an object.
Number Object Methods
Method Description
toExponential(x) Converts a number into an exponential notation
toFixed(x) Formats a number with x numbers of digits after the
decimal point
toPrecision(x) Formats a number to x length
toString() Converts a Number object to a string
valueOf() Returns the primitive value of a Number object
toLocaleString() - Returns a string value version of the current number in a
format that may vary according to a browser's localesettings.
Example:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript toPrecision() Method </title>
</head>
<body>
<script type = "text/javascript">
var num = new Number(7.123456);
[Link]("Maximum Value " + Number.MAX_VALUE);[Link]("<br />");
[Link]("Minimum Value " + Number.MIN_VALUE);[Link]("<br />");
[Link]("[Link](4) is " + [Link](4));[Link]("<br />");
[Link]("[Link](4) is : " + [Link](4));[Link]("<br />");
</script>
</body>
</html>

35
5) W i n d ow O b je ct
The window object represents an open window in a browser.
If a document contain frames (<frame> or <iframe> tags), the browser creates one
window object for the HTML document, and one additional window object for each
frame.
Window Object Methods
Method Description
alert() Displays an alert box with a message and an OK button
blur() Removes focus from the current window
clearInterval() Clears a timer set with setInterval()
clearTimeout() Clears a timer set with setTimeout()
close() Closes the current window
confirm() Displays a dialog box with a message and an OK and a Cancel button
createPopup() Creates a pop-up window
focus() Sets focus to the current window
moveBy() Moves a window relative to its current position
moveTo() Moves a window to the specified position
open() Opens a new browser window
print() Prints the content of the current window
prompt() Displays a dialog box that prompts the visitor for input
resizeBy() Resizes the window by the specified pixels
resizeTo() Resizes the window to the specified width and height
scrollBy() Scrolls the content by the specified number of pixels
scrollTo() Scrolls the content to the specified coordinates
setInterval() Calls a function or evaluates an expression at specified
intervals (in milliseconds)
setTimeout() Calls a function or evaluates an expression after a specified
number of milliseconds
Example : Simple Program on User-defined Function
<html>
<body>
<script type="text/javascript">
function add() // Function Declaration
{
var a = 2,b = 3;
var sum = 0;
sum = a+b;
[Link]("<b>Addition: </b>"+sum);
}
</script>
<p> Click the Button</p>
<input type="button" onClick="add()" value="Click"> //add() -
Calling Function
</body>
</html>

Output:

36
2.6 DHTML (DYNAMIC HYPERTEXT MARKUP LANGUAGE)

DHTML stands for Dynamic Hypertext Markup language i.e., DynamicHTML.


Dynamic HTML is not a markup or programming language but it is a term that
combines the features of various web development technologies for creating the web pages
dynamic and interactive.
Components of Dynamic HTML
DHTML consists of the following four components or languages:
o HTML 4.0
o CSS
o JavaScript
o DOM.
HTML 4.0
HTML is a client-side markup language, which is a core component of the DHTML. It
defines the structure of a web page with various defined basic elements or tags.
CSS
CSS stands for Cascading Style Sheet, which allows the web users or developers for
controlling the style and layout of the HTML elements on the web pages.
JavaScript
JavaScript is a scripting language which is done on a client-side. The various browser
supports JavaScript technology. DHTML uses the JavaScript technology for
accessing, controlling, and manipulating the HTML elements. The statements in
JavaScript are the commands which tell the browser for performing an action.
DOM
DOM is the document object model. It is a w3c standard, which is astandard interface
of programming for HTML. It is mainly used for definingthe objects and properties of
all elements in HTML.
Uses of DHTML
 It is used for designing the animated and interactive web pages thatare
developed in real-time.
 DHTML helps users by animating the text and images in their
documents.
 It allows the authors for adding the effects on their pages.
 It also allows the page authors for including the drop-down menus orrollover
buttons.
 This term is also used to create various browser-based action games.
 It is also used to add the ticker on various websites, which needs torefresh
their content automatically.
Difference between HTML and DHTML
HTML (Hypertext Markup language) DHTML (Dynamic Hypertext Markup
language)
1. HTML is simply a markup language. 1. DHTML is not a language, but it is
a set of technologies of web
development.
2. It is used for developing and 2. It is used for creating and designing
creating web pages. the animated and interactive web sites
or pages.
3. This markup language creates static 3. This concept creates dynamic web
web pages. pages.
37
4. It does not contain any server-side 4. It may contain the code of server-
scripting code. side scripting.
5. The files of HTML are stored with 5. The files of DHTML are stored with
the .html or .htm extension in a the .dhtm extension in a system.
system.
6. A simple page which is created by a 6. A page which is created by a user
user without using the scripts or styles using the HTML, CSS, DOM, and
called as an HTML page. JavaScript technologies called a
DHTML page.
7. This markup language does notneed 7. This concept needs database
database connectivity. connectivity because it interacts with
users.
Example: Webpage using DHTML (HTML + DOM + CSS + JavaScript)
<html>
<head>
<title>
changes the particular HTML element example
</title>
</head>
<body>
<p id="demo"> This text changes color when click on the following different buttons. </p>
<button onclick="change_Color('green');"> Green </button>
<button onclick="change_Color('blue');"> Blue </button>
<script type="text/javascript">

function change_Color(newColor) {
var element = [Link]('demo').[Link] = newColor;
}
</script>
</body>
</html>

38
2.7 JSON introduction – Syntax
JSON stands for Javascript Object Notation. JSON is a text-based dataformat that is
used to store and transfer data.
For example,
// JSON syntax
{
"name": "John",
"age": 22,
"gender": "male",
}
In JSON, the data are in key/value pairs separated by a comma ,.
JSON was derived from JavaScript. So, the JSON syntax resembles JavaScript object
literal syntax. However, the JSON format can be accessed and be created by other
programming languages too.
JSON Syntax
The JSON syntax is a subset of the JavaScript syntax.
JSON Syntax Rules
JSON syntax is derived from JavaScript object notation syntax:
 Data is in name/value pairs.
 The name-value pairs are grouped by a colon (:) and separated by acomma (,)
 Data is separated by commas
 Curly braces hold objects
 Square brackets hold arrays
 An array begins with a left bracket and ends with a right bracket []
 Each key within the JSON should be unique and should beenclosed within
the double quotes.
 The boolean type matches only two special values: true and false and NULL
values are represented by the null literal (without quotes).
 JSON Data - A Name and a Value
 JSON data is written as name/value pairs.
 A name/value pair consists of a field name (in double quotes), followedby a
colon, followed by a value.
 JSON Values
In JSON, values must be one of the following data types:
 a string
 a number
 an object (JSON object)
 an array
 a boolean
 null
In JavaScript values can be all of the above, plus any other valid JavaScriptexpression,
including:
 a function

39
 date
 undefined
Example
"name":"John"
 JSON Object

 JSON Array
JSON array is written inside square brackets . For example,
[]

// JSON array
[ "apple", "mango", "banana"]

// JSON array containing objects[


{ "name": "John", "age": 22 },
{ "name": "Peter", "age": 20 }.
{ "name": "Mark", "age": 23 }
]
 Accessing JSON Data
The JSON object is written inside curly braces { }.

"hobby": {

},

We use the. notation to access JSON data. Its syntax is:

You can access JSON data using the dot notation.


For example,

40
Though the syntax of JSON is similar to the JavaScript object, JSON is
different from JavaScript objects.
JSON JavaScript Object
The key in key/value pair should be in The key in key/value pair can be
double quotes. without double quotes.
JavaScript objects can contain
JSON cannot contain functions. functions.
JSON can be created and used by other JavaScript objects can only be
programming languages. used in JavaScript.

// JavaScript object
const jsonData = { "name": "John", "age": 22 };

JSON Function Files


 A common use of JSON is to read data from a web server, and displaythe data
in a web page.
 JSON Example
This example reads a menu from [Link], and displays the menu ina web
page:
JSON Example
<div id="id01"></div>
<script>
function myFunction(arr) {var
out = "";
var i;
for(i = 0; i<[Link]; i++) {
out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
}
[Link]("id01").innerHTML = out;
}
</script>
<script src="[Link]"></script>
 This chapter will teach you, in 4 easy steps, how to read JSON data,using function
files.
1: Create an array of objects.
 Use an array literal to declare an array of objects.
 Give each object two properties: display and url.
 Name the array myArray:
myArray
var myArray = [
{
"display": "JavaScript Tutorial",
"url": "[Link]
},
41
{
"display": "HTML Tutorial",
"url": "[Link]
},
{
"display": "CSS Tutorial",
"url": "[Link]
}
]
2: Create a JavaScript function to display the array.
Create a function myFunction() that loops the array objects, and displaythe content
as HTML links:

function myFunction(arr) {var


out = "";
r i;
for(i = 0; i < [Link]; i++) {
out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
}
[Link]("id01").innerHTML = out;
}
Call myFunction() with myArray as argument:

myFunction(myArray);
3: Use an array literal as the argument (instead of the array variable):

Call myFunction() with an array literal as argument:

myFunction([
{
"display": "JavaScript Tutorial",
"url": "[Link]
},
{
"display": "HTML Tutorial",
"url": "[Link]
},
{
"display": "CSS Tutorial",
"url": "[Link]
}
]);
4: Put the function in an external js file
Put the function in a file named [Link]:

42
myFunction([
{
"display": "JavaScript Tutorial",
"url": "[Link]
},
{
"display": "HTML Tutorial",
"url": "[Link]
},
{
"display": "CSS Tutorial",
"url": "[Link]
}
]);

Add the external script to your page (instead of the function call):
Add External Script
<script src="[Link]"></script>

43

You might also like