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

Module 2-1

Uploaded by

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

Module 2-1

Uploaded by

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

UNIT-II CLIENT SIDE PROGRAMMING

Java Script: An introduction to JavaScript–


JavaScript DOM Model - Exception-Handling-
Validation-Built-in-objects-Event Handling -
DHTML with JavaScript- JSON introduction–
Syntax – Function Files
Introduction
 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 Live Script, 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 is JavaScript?
JavaScript is the programming language of the web.
It can update and change both HTML and CSS.
It can calculate, manipulate and validate data.

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 or VBScript.
 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.
<script type = “text/javascript”>
[Link](“TutorialRide”);
</script>

 The 'type' attribute indicates which script language you are


using with the type attribute.
Types of Scripts
Client-Side Scripting
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 after they
arrive at the browser.
 It is useful for making the pages a bit more interesting and user- friendly.
 It provides useful gadgets such as calculators, clocks etc.
 It enables interaction within a web page.
 It is affected by the processing speed of the user's computer.
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 during or after
the display.
 Client-Side scripting is used to make web page changes after they arrive 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 understand the
scripting language.
 Server-Side Scripting
 Server-Side Scripting is used in web development.
 The server-side environment runs a scripting language which is called a web server.
 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 and providing 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 be
changed 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 text between 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 scripting language 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>
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.
 Inside <HEAD> tag
 Within <BODY> tag
 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
web pages.
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)
attribute of a <script> tag.
o Example: <script src="[Link]"></script>

External scripts cannot contain <script> tags.


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 line
comment 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 (\S or \$).
Displaying Output in JavaScript
 JavaScript Display Possibilities : JavaScript can "display" data in different ways:
 Writing into an HTML element, using innerHTML.
 Writing into the HTML output using [Link]().
 Writing into an alert box, using [Link]().
 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>
JavaScript Popup/Dialog Boxes
 JavaScript has three kinds of popup/dialog boxes:
 1) Alert box, 2) Confirm box, and 3) Prompt box.
 Alert Box
 An alert box is often used if you want to make sure information comes through to the
user.
 When an alert box pops up, the user will have to click "OK" to
 proceed.
 Syntax; [Link]("sometext");
Confirm Box
 A confirm box is often used if you want the user to verify or accept something.
 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 value before 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 user clicks "Cancel" the box
returns null.
 Syntax: [Link]("sometext","defaultText");
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 car name.
 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.
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";
Assigning Values to Undeclared JavaScript Variables

If you assign values to variables that have not yet been declared, the variables 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. var x=5;
var x;

After the execution of the statements above, the variable x will still have the value of 5. The value of x
is not reset (or cleared) when you redeclare it.
JavaScript Operators
There are different types of JavaScript operators:
•Arithmetic Operators
•Assignment Operators
•Comparison Operators
•String Operators
•Logical Operators
•Bitwise Operators
•Ternary Operators
•Type Operators
Arithmetic Operators are used to perform arithmetic on numbers:
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
JavaScript Assignment Operators
• Assignment operators assign values to JavaScript variables.
• The Addition Assignment Operator (+=) adds a value to a variable.

Operator Example Same As


= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
JavaScript Comparison Operators
Operator Description

== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type

> greater than

< less than

>= greater than or equal to

<= less than or equal to

? ternary operator
JavaScript Logical Operators
Operat Description
or
&& logical and

|| logical or

! logical not

JavaScript Type Operators

Operator
Operator Description
Description

typeof
typeof Returnsthe
Returns thetype
typeof
ofaavariable
variable

instanceof
instanceof Returnstrue
Returns trueififan
anobject
objectisisan
aninstance
instance
ofan
of anobject
objecttype
type
JavaScript Bitwise Operators
Operator Description Example Same as Result Decimal
& AND 5&1 0101 & 0001 1
0001
| OR 5|1 0101 | 0101 5
0001
~ NOT ~5 ~0101 1010 10
^ XOR 5^1 0101 ^ 0100 4
0001
<< left shift 5 << 1 0101 << 1010 10
1
>> right shift 5 >> 1 0101 >> 0010 2
1
>>> unsigned right 5 >>> 1 0101 0010 2
JavaScript Control and Looping Structure
 If Statement
 IF statement is a conditional branching statement.
 In 'IF' statement, if the condition is true a group of
statement is executed. And if the condition is false, the
following statement is skipped.
if(condition)
{
//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>
If – Else Statement
If – Else is a two-way decision statement.
It is used to make decisions and execute statements conditionally.

Syntax : If-Else statement if (condition)


{ <head>

//Statement 1; <script type="text/javascript">

} var no = prompt("Enter a Number to find Odd or Even");

else if(condition) no = parseInt(no);

{ if (isNaN(no))

//Statement 2; {

} alert("Please Enter a Number");

else }

{ else if (no == 0)

//Statement 3; {

} alert("The Number is Zero");


}
else if (no % 2)
{
alert("The Number is Odd");
else
{
alert("The Number is Even");
}
</script>
</head>
</html>
Switch Statement
Switch is used to perform different actions on different conditions.
It is used to compare the same<html>
expression to several different values.
<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>
For Loop
For loop is a compact form of looping.
It includes three important parts:
Loop Initialization
Test Condition
Iteration
All these three parts come in a single line separated by semicolons(;).

Syntax:
for(initialization; test-condition;
increment/decrement)
{
Syntax
//Statements;
}
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.

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

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 at the end of the
loop.
The loop is executed at least once, even if the condition is false.

<html>
<body>
<script type Output:
="text/javascript"> 0
var i = 0; 1
2
do{ 3
[Link](i+"<br>") 4
i+ 5

+;
}
while (i <= 5)
</script>
</body>
</html>
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
program. condition.
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
terminates the loop. conditional is false.
It is a counter-controlled loop. It is a iterative control loop.
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 .

 Syntax: break;
Continue Statement
Continue statement causes the loop to continue with the next
iteration.
It skips the remaining code block.

 Syntax:
Continue;
JavaScript Functions
 A JavaScript function is a block of code designed to perform a particular task.
 A JavaScript function is executed when "something" invokes it (calls it).

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 through the
(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 returns NaN.
parseInt If the string begins with an integer, the function reads through the
(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 returns NaN
(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.
You can 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 ---- Syntax:
followed by parentheses ().
function name(parameter1, parameter2,
 Function names can contain letters, digits, parameter3)
underscores, and dollar signs
{
 (same rules as variables).
// code to be executed
 The parentheses may include parameter
}
names separated by commas:
 (parameter1, parameter2, ...)
 The code to be executed, by the function, is
placed inside curly brackets: {}
Example :
function myFunction(p1, p2)
{
return p1 * p2; // The function returns the product of p1 and p2
}

 Function Invocation  Function Return


 The code inside the function  When JavaScript reaches a
will execute when "something" return statement, the function
invokes (calls) the function: will stop executing.
 When an event occurs (when a  If the function was invoked
user clicks a button) from a statement, JavaScript
 When it is invoked (called) from will
JavaScript code  "return" to execute the code
 Automatically (self invoked) after the invoking statement.
 Functions often compute a
return value. The return value
is "returned" back to the
"caller―.
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>
JavaScript Arrays
Creating and Initializing Arrays

 Array is a grouping of objects



var variable_name = new Array(); // Creating
It stores multiple values in a
an Array
single variable

var arr = []; // Creating an Array
It stores a fixed-size sequential
collection of elements of the var arr1 = [1, 2, 3]; // Initializing an Array
same type. Multidimensional Array
 It is used to store collection of
data. var arr2 = [
[1, 2, 3] , ['a', 'b', 'c'], ['x', 'y', 'z']
];
Array Properties

Array Description
Properti
 Iteration through Arrays es
 function show_array(arr)

Constructor It returns a reference to the array
{
function that created the object.
 for (var i = 0; i < [Link]; i++ )
 {
 [Link](array[i]);
Index It represents the zero-based index of the
[Link]('<br/>'); match in the string.
 }
 } Length It reflects the number of elements in an
 var arr1 = [1, 2,3]; array.
 show_array(arr1); Input It presents only an array created by
regular expression matches.

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 other arrays and values.
every() It returns true if every element in this array
satisfies the provided testing function.
filter() It creates a new +rray with all the elements of this
array for which the provided filtering function returns
true.
indexOf It returns the first index of an element within the array
() equal to the specified value.
join() It joins all elements of an array into a string.
pop() It removes the last element from an array and returns
that element.
push() It adds one or more elements to the end of an array
and returns the new length of the array.
reverse( It reverses the order of the elements of an array.
)
Example: Program on Array Methods – POP() S PUSH()
<html> function arrpush()
<body> {
<button onclick="arrpop();">POP</button>
var numbers = ["1","2","3","4","5","6"]
<button onclick="arrpush();"> PUSH
</button> [Link]("7");
<script> // now we got ["1","2","3","4","5","6"]
function arrpop() [Link]("Added element
{ is :"+" "+numbers[[Link]-1])
var numbers = ["1", "2", "3", "4", "5", // Now we have [1,2,3,4,5,6]
"ABC"];
[Link]("<br>"+"Now length
[Link]([Link]()+" is: "+[Link]); // 7 Added
"+"Removed"+"<br>");
}
//pop() removes the last element of an array
</script> OUTPUT
// Now we have [1,2,3,4,5] </body>
[Link]("Now length is:
</html>
"+[Link]); // ABC removed
}
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 and


traversal within the documents.
DOM 3 – Current release published in 2004. It could deal with XML with 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.
2u .m2 e: nJtavaScript DOM
The HTML DOM model is constructed as a tree of Objects: Doc
Model

<html>
<head>
<head>
<title>My Page</title>
<body> <title>
</head>
<body> <h1>
<h1> Hello! </h1>
</body>

</html>
• At the top level, there is an html node, with two children: head and
body, among which only head has a child tag title.
• HTML tags are element nodes in DOM tree, pieces of text becomet
ext nodes. Both of them are nodes, just the type is different.
ACCESSING DOM:

My PageHello!

The HTML DOM can be accessed with JavaScript (and with other
programming languages).
✓ In the DOM, all HTML elements are defined as objects.
✓ With the object model, JavaScript gets all the power it needs to
create dynamic 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
The following table lists the node types commonly encountered
in HTML documents 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
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 web page.
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 do this:
· 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


me()
[Link] Find elements by class name
ame()
Changing HTML Elements
Method Description
[Link]= Change the inner HTML of an element
[Link]= Chan
ge the attribute of an HTML element
[Link](attribute,val Change the attribute of an HTML
ue) 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

[Link](text) Write into the HTML output


stream

Adding Events Handlers

Method Description
Adding event
[Link](id).onclick=function() handler code to an
{code}
onclick event
Reacting to Events
✓ A JavaScript can be executed when an event occurs, like when a user clicks on
an HTML element.
✓ To execute code when a user clicks on an element, add
JavaScript code 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

· When an input field is changed

· When an HTML form is submitted

· When a user strokes a key


<!DOCTYPE html>
</script>
<html>
</head>
<head> <body onload="Display()">
<script type="text/javascript"> var <p class="exp">Example for Accessing
page_element=""; function end() Elements</p>
{ <div id="main">
var txt=[Link]("end of <p>The DOM is very useful.</p>
document"); <p id="demo"></p>
[Link](txt); </div>
} <p class="exp">Thank You</p>
function Display() // function <script>
definition var x = [Link]("main");
{ var y = [Link]("p");
for(i=0;i<[Link];i++) y[1].innerHTML = "Welcome DOM";
{ var
page_element+="<br>"+[Link][i]. z=[Link]("ex
tagName; // accessing all the p");
elements using DOM z[0].[Link]="blue";
} z[1].[Link]="Green";
[Link]="center"; // accessing </script>
element's atrribute <p id="pmsg" > <strong> Various
[Link]+=page_element;// Elements used in this web documents
setting the element's text
What is form validation?
➢ Form validation is the process of checking the forms that have been filled in correctly before they
are processed.
➢ It provides a method to check the user entered information on client-side
before 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.
[Link] //File name
<html>
<body>
<script>
function validateemail()
{
var a =
[Link]; var
atposition = [Link]("@");
var dotposition = [Link](".");
[Link] //File name
if (atposition<1 || dotposition<atposition+2 ||
dotposition+2>=[Link]) <html>
{ <body>
<script
alert("Please Enter a valid type="text/java
E-mail Id"); return false; script">
alert("You are a
}
Valid User
} !!!");
</script> </script>
</body>
</body> </html>
<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>
<!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!@#$%^S*()_]{6,20}$/;

function validate(){
var name = [Link]; var email = [Link];
var username = [Link]; var password = [Link]; var gender =
[Link];
var errors = [];
if (!ck_name.test(name)) { if ([Link] > 0) { reportErrors(errors); return false;
errors[[Link]] = "Enter your valid }
Name ."; } return true;
}
if (!ck_email.test(email)) {
errors[[Link]] = "You must enter a function reportErrors(errors){
valid email address.";
var msg = "Please Enter Valide Data...\n"; for (var i = 0;
} i<[Link]; i++) {
if (!ck_username.test(username)) { var numError = i + 1;

errors[[Link]] = "You must enter valid msg += "\n" + numError + ". " + errors[i];
UserName with no special char ."; }
} alert(msg);
}
if (!ck_password.test(password)) { </script>
errors[[Link]] = "You must enter a </head>
valid Password min 6 char."; <body>
}
if (gender==0) { <center> REGISTRATION FORM</center> <hr>
errors[[Link]] = "Select Gender"; <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>
<input type="submit" value="Submit" onclick="return
validate()">
</form>
</body>
Explain the DOM Event handling with suitable example
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.

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
handler Applies to: Triggered when:
onAbort Image The loading of the image is
cancelled.
onBlur Button, Checkbox, The object in question loses
Password, Radio, focus (e.g. by clicking outside it
Reset, Select, Submit, or pressing the TAB key).
Text, TextArea,
Window
onChange Select, Text, TextArea The data in the form element is
changed by the
user.
onClick Button, Checkbox, The object is clicked on.
Link, Radio, Reset,
Submit
onDblClick Document, Link The object is double-clicked on.
onError Image A JavaScript error occurs.
onFocus Button, Checkbox, The object in question gains
Password, Radio, focus (e.g. by clicking on it or
Reset, Select, pressing the TAB 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.
onMouseDo Button, Link The user presses a mouse button.
wn
onMouseMo None The user moves the mouse.
ve
onMouseOut Image, Link The user moves the mouse away
from the object.
onMouseOver Image, Link The user moves the mouse over
the object.
onMouseUp Button, Link The user releases a mouse
button.
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.
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.
1. Traditional Model: Registering event handler through DOM.
Example:
<!DOCTYPE html>
<html>
<head>
<title> Event Handling in JavaScript</title>
<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 incorrect. There 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 missing a closing
parenthesis.
<script type = "text/javascript">
<!--
[Link](;
//-->
</script>
When a syntax error occurs in JavaScript, only the code
contained within the same thread as the syntax error is affected
and the rest of the code in other threads gets executed assuming
nothing in them depends on the code containing the error.
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.
You cannot catch those errors, because it depends on your business requirement what type of logic you
want to put in your program.

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>
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue
normal execution.
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:

3. EvalError: It creates an instance for the error that occurred in the eval(), which is a global function
used for evaluating the js string code.
4. InternalError: It creates an instance when the js engine throws an internal error.
5. RangeError: It creates an instance for the error that occurs when a numeric variable or parameter is
out of its valid range.
6. ReferenceError: It creates an instance for the error that occurs when an invalid reference is de-
referenced.
7. SyntaxError: An instance is created for the syntax error that may occur while parsing the eval().
8. TypeError: When a variable is not a valid type, an instance is created for such an error.
9. URIError: An instance is created for the error that occurs when invalid 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
or one 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.
<!DOCTYPE html> try
<html> {
<body> if(x == "") throw "is empty";

<p>Please input a number between 5 and if(isNaN(x)) throw "is not a number";
10:</p> x =Number(x); if(x > 10) throw "is too high"; if(x <
5) throw "is too low";
}
<input id="demo" type="text">
catch(err)
<button type="button"
onclick="myFunction()">Test {
Input</button> [Link] = "Input " + err;
}
<p id="p01"></p> finally
{

<script> [Link]("demo").value = "";


}
function myFunction()
}
{ var message, x;
</script>
message =
[Link]("p01"); </body>
[Link] = ""; </html>
x=[Link]("demo").val
The throw Statement

You can use throw statement to raise your built-in exceptions or your customized
exceptions. Later these exceptions can be captured and you can take an appropriate
action.

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)
1) Math Object
Math object is a built-in static object.
It is used for performing complex math operations.
Math Properties
Math Description
Property
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.
log() Returns the natural logarithm (base E) of a number.
EXAMPLE:
<html>
Output
<head>
<title>JavaScript Math Object Methods</title>
ABS Test Value : 20
</head>
<body> ACOS Test Value :
<script type="text/javascript"> 3.14159265358979
var value = [Link](20); ASIN Test Value :
[Link]("ABS Test Value : " + value +"<br>"); 1.57079632679482
ATANTest
var value = [Link](-1); Value:
[Link]("ACOS Test Value : " + value +"<br>"); 0.46364760900080

var value = [Link](1);


[Link]("ASIN Test Value : " + value +"<br>");

var value = [Link](.5);


[Link]("ATAN Test Value : " + value +"<br>");
</script>
</body>
</html>
1) 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 fie
Syntax:
var variable_name = new Date();
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.
getTimezoneOffset() Returns the timezone offset in minutes for the current
locale.
getMonth() Returns the month.
setDate() Sets the day of the month.
setFullYear() Sets the full year.
<html>
<body>
<center>
<h2>Date Methods</h2>
<script type="text/javascript">
var d = newDate();
[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>
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);

Properties Description
length It returns the length of the string.
prototype It allows you to add properties and methods to an
object.
construct It returns the reference to the String function that
or created the object.
String Methods

Methods Description

charAt() It returns the character at the specified index.

charCodeA It returns the ASCII code of the character at the specified


t() position.

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 new


substring.

search() It executes the search for a match between a regular


expression.

slice() It extracts a session of a string and returns a new string.


<html>
<body>
<center>
<script
type="text/javascript"> var
str = "CareerRide Info"; var
s = [Link]();
[Link]("<b>CharAt:</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>
Boolean Object

The Boolean object is used to convert a non-Boolean value to a


Boolean value (true or false).

Syntax
Use the following syntax to create a boolean
object. var val = new Boolean(value);

Method Description

toString() Converts a Boolean value to a string, and returns the result

valueOf() Returns the primitive value of a Boolean object


DHTML

DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML.
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
DOM
DOM is the document object model. It is a w3c standard, which is a
standard interface of programming for HTML. It is mainly used for
defining the objects and properties of all elements in HTML.
Uses of DHTML

✓ It is used for designing the animated and interactive web pages that are 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 or rollover 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 to refresh their
content automatically.
HTML (Hypertext Markup language) DHTML (Dynamic Hypertext Markup
language)

J 1. DHTML is not a language, but it is a set of


1. HTML is simply a markup language. technologies of web development.

2. It is used for developing and creating 2. It is used for creating and designing the
web pages. animated and interactive
web sites or pages.

3. This markup language creates static web 3. This concept creates dynamic web pages.
pages.

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 the .html 5. The files of DHTML are stored with the .dhtm
or .htm extension in a system. extension in a system.

6. A simple page which is created by a user 6. A page which is created by a user using the
without using the scripts or styles called as an HTML, CSS, DOM, and JavaScript technologies
HTML page. called a DHTML page.

7. This markup language does not need 7. This concept needs database connectivity
database 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>
JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format.
It is based on a text format that is easy for humans to read/write and easy for machines
to parse/generate.
JSON is language-independent, but it uses conventions familiar to C, C++, Java, and
JavaScript.
Widely used in APIs, web services, and data storage.

1. JSON Syntax

The JSON syntax is a subset of the JavaScript syntax

{
"student": {
"name": "Ravi",
"age": 21,
"marks": [85, 90, 92],
"isPassed": true
}
}
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 a comma (,)
✓ 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 be enclosed
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), followed by a colon, followed
by a value.

❖ JSON Values
In JSON, values must be one of the following data types:

•Strings: Text enclosed in double quotes.


•Numbers: Integers or floating-point numbers.
•Booleans: true or false.
•null: Represents an empty or nonexistent value.
•Objects: Can contain nested objects.
•Arrays: Can contain nested arrays.
In JavaScript values can be all of the above, plus any other valid JavaScript expression, including:

• a function
• a date
• undefined
JSON Functions in JavaScript
JavaScript provides two main functions:
[Link]. parse() → Converts JSON string into a JavaScript object.

let text = '{"name": "Ravi", "age":21}';


let obj = JSON. parse(text);
[Link]([Link]); // Output: Ravi
JSON. stringify() → Converts JavaScript object into JSON
2.
string.
let student = { name: "Ravi", age: 21 };
let json Text = JSON. stringify(student);
[Link](json Text);

// Output: {"name":"Ravi","age":21}

You might also like