Wp-Unit-3 Part-1
Wp-Unit-3 Part-1
UNIT - III
JAVASCRIPT
Objective:
To develop interactive web applications.
Validate HTML forms
Syllabus:
Java Script: Introduction to Javascript, variables, primitive data types, control flow statements,
Built-in objects, arrays, functions, event handling, DHTML - Object model.
Learning Outcomes:
Convert static HTML page to dynamic web page by adding JavaScript code
Create variables; use data types, operators and functions in writing JavaScript programs.
Develop simple applications using various Control flow Statements.
Use various pre-defined Objects in JavaScript while developing simple programs.
Can dynamically change content on a web page by using JavaScript Event Handlers.
Validate HTML form elements using DHTML and JavaScript.
LEARNING MATERIAL
Advantages of JavaScript:
You can validate the user input before sending the page off to the server. This saves
server traffic, which means less load on server.
If you submit a form if there is any error in form filling immediately visitor get the
feedback, because validation performed at client side.
JAVA Vs JAVASCRIPT:
JAVA JAVASCRIPT
1. Object Oriented Programming
2.1 Object based Scripting Language
Language
2. Platform Independent 2.2 Browser Dependant
3. It is both compiled and interpreted 2.3 It is interpreted at runtime
4. It is used to create server side
2.4 It is used to make the web pages more
applications and standalone
interactive
programming
2.5 JavaScript is not strongly typed(Loosely
5. Java is a strongly typed language
Typed)
6. Developed by sun Microsystems 2.6 Developed by Netscape
2.7 JavaScript must be placed inside an
7. Java Programs can be standalone
HTML document to function
Embed a JavaScript in an HTML document by using <script> and </script> html tags.
Syntax:
<script ...>
JavaScript code
</script>
Example:
<html>
<body>
<script language="javascript" type="text/javascript">
document.write ("Hello World!")
</script>
</body>
</html>
<html>
<head>
<title>My First JavaScript code!!!</title>
<script type="text/javascript">
alert("Hello World!");
</script>
</head>
<body>
</body>
</html>
Output:
alert(“Hello World”);
Var d= confirm(“Do you want to continue?”);
Var i=prompt(“Enter your name:”,”SRGEC”);
Comments in JavaScript:
JavaScript supports both C-style and C++-style comments. Thus:
Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.
Any text between the characters /* and */ is treated as a comment. This may span
multiple lines.
VARIABLES:
• Like any programming language JavaScript has variables.
• Stores data items used in the script.
• Strict rules governing how you name your variables (Much like other languages):
Creating Variables
• Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword as follows.
<script type="text/javascript">
var name;
var rollno;
</script>
<script type="text/javascript">
var name = “Aziz”;
var rollno=501;
</script>
The scope of a variable is the region of your program in which it is defined and is accessible.
JavaScript variables have only two scopes.
Global Variables: A global variable has global scope which means it can be defined and
used anywhere in your JavaScript code.
Local Variables: A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
Automatically Global:
• If you assign a value to a variable that has not been declared, it will automatically
become a GLOBAL variable.
• This code example will declare a global variable price, even if the value is assigned
inside a function.
Example:
Var price=300;
Rate=20;
function myFunction()
{
var price = 250; //has Global scope
}
document.write(price);
Example:
<script language="javascript" type="text/javascript">
var collegename="GEC college"; //global scope
function function1()
{
var studentname="Anand";//local scope
document.write("<center>"+studentname+"</center><br>");
document.write("<center>"+collegename+"</center><br>");//global scope
}
function function2()
{
var branchname="Information Technology";//local scope
document.write("<center>"+branchname+"</center><br>");
document.write("<center>"+collegename+"</center><br>");//global scope
document.write("<center>"+studentname+"</center>");//not displayed because of local
scope
}
function1();
function2();
</script>
DATA TYPES:
JavaScript has only four types of data
Numeric
String
Boolean
Null
Numeric :
Integers such as 108 or 1120 or 2016
Floating point values like 23.42, -56.01 and 2E45.
No need to differentiate between.
In fact variables can change type within program.
String:
A String is a Collection of character.
All of the following are strings:
"Computer", "Digital" , "12345.432".
Put quotes around the value to a assign a variable:
name = "Uttam K.Roy";
Boolean:
Variables can hold the values true and false.
Used a lot in conditional tests (later).
Null:
Used when you don’t yet know something.
A null value means one that has not yet been decided.
It does not mean nil or zero and should NOT be used in that way.
FUNCTIONS:
• A function is a group of reusable code which can be called anywhere in your program.
• This eliminates the need of writing the same code again and again.
• It helps programmers in writing modular codes. Functions allow a programmer to divide
a big program into a number of small and manageable functions.
• Like any other advanced programming language, JavaScript also supports all the features
necessary to write modular code using functions.
• We were using these functions again and again, but they had been written in core
JavaScript only once.
• JavaScript allows us to write our own functions as well.
Function Definition
Before we use a function, we need to define it.
The most common way to define a function in JavaScript is
By using keyword function, followed by a unique function name, a list of parameters
(that might be empty), and a statement block surrounded by curly braces.
Syntax:
<script type="text/javascript">
function functionname(parameter-list)
{
statements
}
</script>
Example:
<html>
<head>
<title>My First JavaScript code!!!</title>
<script type="text/javascript">
function sayHello()
{
document.write("Hello How are
you...?");
}
sayHello();//calling function
</script>
</head>;
<body>
</body>
</html>
Calling a Function:
To invoke a function somewhere later in the script, you would simply need to write the
name of that function as shown in the following code.
<html>
<head>
<title>Calling a function</title>
<style type='text/css'>
*
{
text-align:center;
}
</style>
<script type="text/javascript">
function sayHello()
{
var name=form.name.value;
document.write("Hello "+name+" Good Morning");
}
</script>
</head>
<body>
<p>Please enter you name and click the button to get wishes</p></br>
<form name='form'>
<input type='text' name='name' placeholder='Enter Name'><br><br>
<input type='button' value='click here' onclick='sayHello();'>
</form>
</body>
</html>
Output:
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical (or Relational) Operators
Conditional (or ternary) Operators
CONTROL FLOW STATEMENTS: These statements allow you to control the flow of your
program’s execution based upon conditions known only during run time.
The if Statement
Syntax
if (condition)
{
block of code to be executed if the condition is true
}
}
else
{
block of code to be executed if the condition is false
}
Example:
<HTML>
<HEAD>
<script>
function check()
{
var age=form.age.value;
if(age>=18)
{
alert("You are eligible for vote");
}
else
{
alert("You are not eligible for vote");
}
}
</script>
</HEAD>
<BODY>
<form name='form'>
<p>Enter your age and check whether you are eligible for vote or not?</p><br>
<input type='text' name='age'><br><br>
<input type='button' value='check eligibility' onclick='check();'>
</form>
</BODY>
</HTML>
Output:
Syntax:
if (condition1)
{
block of code to be executed if condition1 is true
}
else if (condition2)
{
block of code to be executed if the condition1 is false and condition2 is true
}
else
{
block of code to be executed if the condition1 is false and condition2 is false
}
Example:
<HTML>
<HEAD>
<script>
function check()
{
var percentage=form.percentage.value;
if(percentage>=90&&percentage<=100)
{
alert("Your grade is A+");
}
else if(percentage>=75&&percentage<90)
{
alert("Your grade is A");
}
else if(percentage>=60&&percentage<75)
{
alert("Your grade is B");
}
else if(percentage>=40&&percentage<60)
{
alert("Your grade is C");
}
else if(percentage>100)
{
alert("Wrong details .... ");
}
else
{
alert("You are failed");
}
}
</script>
</HEAD>
<BODY>
<form name='form'>
<p>Enter your marks to know your grade</p><br>
<input type='text' name='percentage' placeholder='EX:70.45/70'><br><br>
<input type='button' value='check grade' onclick='check();'>
</form>
</BODY>
</HTML>
Output:
Switch Statement:
Use the switch statement to select one of many blocks of code to be executed.
Syntax:
switch(expression) {
case 1:
code block
break;
case 2:
code block
break;
case n:
code block
break;
default:
default code block
}
break;
case "ST":
alert("45 vanacies");
break;
case "OBC":
alert("20 vanacies");
break;
default:
alert("please enter valid category");
break;
}
}
</script>
</HEAD>
<BODY>
<form name='form'>
<p>Please enter your category to check no of vacanices</p><br>
<input type='text' name='category'
placeholder='EX:OC/BC/OBC/SC/ST'><br><br>
<input type='button' value='Check Vacancies' onclick='check();'>
</form>
</BODY>
</HTML>
Output:
while (condition)
{
code block to be executed
}
Example:
<HTML>
<HEAD>
<script>
function check()
{
var number=form.number.value;
var i=1;
while(i<=number)
{
if(i%2==0)
document.write("<center>"+i+"</center><br>");
i++;
}
}
</script>
</HEAD>
<BODY>
<form name='form'>
<p>Find o to n even numbers</p><br>
<input type='text' name='number'><br><br>
<input type='button' value='Get Even Numbers' onclick='check();'>
</form>
</BODY>
</HTML>
Output:
The do/while loop is a variant of the while loop. This loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as long as the condition
is true.
Syntax
do
{
code block to be executed
}while (condition);
The for Loop: The for loop has the following syntax:
for (initialization; condition; iteration)
{
code block to be executed
}
Example:
Example 2:
<BODY>
<form name='form'>
<p>Enter a number to know the factorial</p><br>
<input type='text' name='number'><br><br>
<input type='button' value='Get Factorial' onclick='check();'>
</form>
</BODY>
</HTML>
Output:
An Object is a thing.
There are pre defined objects and user defined objects in Javascript.
Document
Window
Browser/Navigator
Form
String
Math
Array
Date
HTML DOM
The way document content is accessed and modified is called the Document Object Model, or
DOM.
In the HTML DOM (Document Object Model), everything is a node:
The document itself is a document node
All HTML elements are element nodes
All HTML attributes are attribute nodes
Text inside HTML elements are text nodes
Comments are comment nodes
The Objects are organized in a hierarchy. This hierarchical structure applies to the organization
of objects in a Web document.
Window object − Top of the hierarchy. It is the outmost element of the object hierarchy.
Document object − Each HTML document that gets loaded into a window becomes a
document object. The document contains the contents of the page.
Form object − Everything enclosed in the <form>...</form> tags sets the form object.
Properties
alinkColor - The color of active links
Sets the background color of the web page. It is set in the <body>
bgColor -
tag. The following code sets the background color to white.
The name of the current document as described between the header
Title -
TITLE tags.
URL - The location of the current document.
Methods
getElementById(id) - Find an element by element id
getElementsByTagName(name) - Find elements by tag name
getElementsByClassName(name) - Find elements by class name
write(text) - Write into the HTML output stream
writeln(text) - Same as write() but adds a new line at the
end of the output
WINDOW OBJECT:
The window object is supported by all browsers. It represents the browser's window.
All global JavaScript objects, functions, and variables automatically become members of
the window object.
Global variables are properties of the window object.
Global functions are methods of the window object.
Even the document object (of the HTML DOM) is a property of the window object:
window.document.getElementById("header");
is the same as:
document.getElementById("header");
Properties
defaultStatus - This is the default message that is loaded into the status bar when the window
loads.
opener The object that caused the window to open.
status - The status bar is the bar on the lower left side of the browser and is used to display
temporary messages
length - The number of frames that the window contains.
Methods
alert("message") - The string passed to the alert function is displayed in an alert dialog box.
open("URLname","Windowname",["options"]) - A new window is opened with the name
specified by the second parameter.
close() - This function will close the current window or the named window.
confirm("message") The string passed to the confirm function is displayed in the confirm
dialog box.
prompt("message","defaultmessage") - A prompt dialog box is displayed with the message
passed as the prompt question or phrase.
Example:
<HTML>
<HEAD>
<script>
function funalert()
{
window.alert("Hello be alert .... ");
}
function funopen()
{
window.open("http://www.gmail.com");
}
function funprompt()
{
window.prompt("Do you want to exit?");
}
function funconfirm()
{
window.confirm("Do you want to exit?");
}
function funclose()
{
window.close();
}
</script>
</HEAD>
<BODY>
<form>
<input type='button' value='click here for alert()' onclick='funalert()'>
<input type='button' value='click here for open()' onclick='funopen()'>
<input type='button' value='click here for prompt()' onclick='funprompt()'>
<input type='button' value='click here for cofirm()' onclick='funconfirm()'>
<input type='button' value='click here for close()' onclick='funclose()'>
</form>
</BODY>
</HTML>
Output:
FORM OBJECT:
Properties
String The string object allows you to deal with strings of text.
Properties
Methods:
toUpperCase() - Returns a copy of the string with all characters in upper case.
Example:
<HTML>
<HEAD>
<script>
<BODY>
</BODY>
</HTML>
Output:
ARRAY OBJECT:
The Array object is used to store multiple values in a single variable.
Properties:
length - Sets or returns the number of elements in an array
Methods:
concat() - Joins two or more arrays, and returns a copy of the joined arrays
indexOf() - Search the array for an element and returns its position
join() - Joins all elements of an array into a string
lastIndexOf() - Search the array for an element, starting at the end, and returns its
position
pop() - Removes the last element of an array, and returns that element
push()- Adds new elements to the end of an array, and returns the new length
reverse() - Reverses the order of the elements in an array
shift() - Removes the first element of an array, and returns that element
slice() - Selects a part of an array, and returns the new array
sort() - Sorts the elements of an array
splice() - Adds/Removes elements from an array
toString() - Converts an array to a string, and returns the result.
Example:
<HTML>
<HEAD>
<script>
var cars = new Array("Saab", "Volvo", "BMW");
var bikes = new Array("Pulsar", "Honda", "FZ");
document.write("<center>"+cars.concat(bikes)+"</center>");
document.write("<center>"+cars.indexOf("Volvo")+"</center>");
bikes.push("Bajaj");
document.write("<center>"+bikes+"</center>");
bikes.reverse();
document.write("<center>"+bikes+"</center>");
cars.sort();
document.write("<center>"+cars+"</center>");
</BODY>
</HTML>
Output:
</script>
</HEAD>
<BODY>
</BODY>
</HTML>
Output:
Math Object:
The math object provides you properties and methods for mathematical constants and functions.
Unlike other global objects, Math is not a constructor. All the properties and methods
of Math are static and can be called by using Math as an object without creating it.
Thus, you refer to the constant pi as Math.PI and you call the sine function as Math.sin(x),
where x is the method's argument.
Math Properties (Constants)
JavaScript provides 8 mathematical constants that can be accessed with the Math object:
Example
Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
Method Description
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2
radians
Example:
<HTML>
<HEAD>
<script>
document.write("<center>"+Math.PI+"</center><br>");
document.write("<center>"+Math.ceil(0.991)+"</center><br>");
</script>
</HEAD>
<BODY>
</BODY>
</HTML>
Output:
EVENT HANDLING:
JavaScript is an Event Driven System
Event:
An Event is “any change that the user makes to the state of the browser”
There are 2 types of events that can be used to trigger script:
1. Window Events
2. User Events
1. Window Events, which occurs when
A page loads or unloads
Focus is being moved to or away from a window or frame
Examples:
1. <html>
<head>
<script language="javascript">
function fun()
{
alert("Page is Loaded");
}
</script>
</head>
<body onload="fun()">
</body>
</html>
Output:
2. <html>
<head>
<script language="javascript">
function fun()
{
alert("You Clicked on Button");
}
</script>
</head>
<body>
<input type="button" value="Click Me" onClick="fun()">
</body>
</html>
Output:
<HTML>
<HEAD>
<script>
function check()
{
var number=form.number.value;
var i=1;
while(i<=number)
{
if(i%2==0)
document.write("<center>"+i+"</center><br>");
i++;
}
}
</script>
</HEAD>
<BODY>
<form name='form' onSubmit='check();'>
<p>Find 1 to n even numbers</p><br>
<input type='text' name='number'><br><br>
<input type='submit' value='Get Even Numbers'>
</form>
</BODY>
</HTML>
Output:
HTML Vs DHTML
HTML DHTML
1. It is used to create static web 1. Used to create dynamic web
pages. pages.
2. Made up of HTML
2. Consists of simple HTML tags.
tags+CSS+javascript+DOM
3. It is a technique to make web
3. It is a markup language. pages dynamic through client-side
programming.
4. DHTML allows you to alter the
4. Do not allow to alter the text and
text and graphics of the web page
graphics on the web page unless
without changing the entire web
web page gets changed.
page.
5. Creation of HTML web pages is 5. Creation of DHTML web pages is
simple. complex.
6. Web pages are less interactive. 6. Web pages are more interactive.
7. HTML sites will be slow upon 7. DHTML sites will be fast enough
client-side technologies. upon client-side technologies.
Form Validation:
Form validation normally used to occur at the server, after the client had entered all the
necessary data and then pressed the Submit button. If the data entered by a client was incorrect
or was simply missing, the server would have to send all the data back to the client and request
that the form be resubmitted with correct information. This was really a lengthy process which
used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending it to
the web server. Form validation generally performs two functions.
Basic Validation − First of all, the form must be checked to make sure all the mandatory
fields are filled in. It would require just a loop through each field in the form and check
for data.
Data Format Validation − Secondly, the data that is entered must be checked for
correct form and value. Your code must include appropriate logic to test correctness of
data.
Login.html
<!DOCTYPE html>
<html>
<head>
<title> Login Page </title>
<script>
let a=0;
function userval()
{
a++;
var u = /^[a-zA-Z\-]+$/;
var user=document.getElementById("t1").value;
if(user.match(u)==null)
alert("Only alphabets are allowed");
document.login.user.focus();
}
function pswval()
{
a++;
var pwd=document.getElementById("p1").value;
var p=/^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[~`!@#$%^&*()--+={}\[\]|\\:;"'<>,.?/_◻])[a-zA-Z0-
9~`!@#$%^&*()--+={}\[\]|\\:;"'<>,.?/_◻]{10,16}$/;
if(!p.test(pwd))
alert("Password must contains atleast 10 Characters with 1 digit 1 upper case and one special symbol");
document.login.psw.focus();
}
function display()
{
if(a==2)
{ alert("Login successful...");
}
else
{alert("Must enter user id and password");
document.login.user.focus();
}
}
</script>
</head>
<body bgcolor="#00ffff"align='center'>
<form name="login">
<h3> <u> Login Page </u> </h3>
username: <input type="text" id="t1" name="user" onchange="userval()"/> <br>
Registration.html
<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
<script>
let a=0;
function nameval(t)
{
a++;
var u = /^[a-zA-Z\-]+$/;
var user=t.value;
if(user.match(u)==null)
alert("User allows only alphabets");
document.f.fname.focus();
}
function pswval()
{a++;
var p=/^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[~`!@#$%^&*()--+={}\[\]|\\:;"'<>,.?/_?])[a-zA-Z0-
9~`!@#$%^&*()--+={}\[\]|\\:;"'<>,.?/_?]{10,16}$/;
var pwd=document.getElementById("p1").value;
if(!p.test(pwd))
alert("Password must contains minimum 10 character and atleast 1 digit 1 upper case and one special
symbol");
document.f.psw1.focus();
}
function cpswval()
{
a++;
function emailval()
{
a++;
var mail=document.getElementById("m1").value;
var m=/[a-z0-9]+@[a-z]+\.[a-z]{2,3}$/;
if(!m.test(mail))
alert("Wrong mail id format");
document.f.email.focus();
}
function mobileval()
{
a++;
var mobile=document.getElementById("m2").value;
var mob=/[6-9]\d{9}$/gi;
if(!mob.test(mobile))
alert("Wrong Mobile number");
document.f.mobile.focus();
}
function display()
{
if(a==5&&document.getElementById("s").value!="select")
{
alert("Registred Successfully...");
return true;
}
else
{
if(document.getElementById("t1").value==""||document.getElementById("p1").value==""||document.g
etElementById("p2").value==""||document.getElementById("m1").value==""||document.getElementBy
Id("m2").value==""||document.getElementById("s").value==="select")
alert("Must fill all the fields");
return false;
}
}
</script>
</head>
<body bgcolor="#00ffff" align='center'>
<center>
<form name="f">