0% found this document useful (0 votes)
99 views106 pages

ES5

Uploaded by

covidgamer00
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)
99 views106 pages

ES5

Uploaded by

covidgamer00
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
You are on page 1/ 106

JavaScript

Introduction:

• JavaScript is a dynamic computer programming language.


• It is lightweight and most commonly used as a part of web pages.
• Javascript implementations allow client-side script to interact with the
user and make dynamic pages.
• It is an interpreted programming language with object-oriented
capabilities.
Dynamic means that variables can hold values of different types during
runtime.
let x = 5; // x is a number
x = "Hello"; // x is now a string
x = [1, 2, 3]; // x is now an array
• European Computer Manufacturers Association (ECMAScript) or (ES)
is a standard for scripting languages like JavaScript, ActionScript and
Jscript.
Advantages:

1. Less server interaction


2. Immediate Feedback to the visitors
3. Increased interactivity
4. Rich Interfaces
Introduction: ES5
• Data Types:
• JavaScript allows you to work with three primitive data types −
• Numbers, eg. 123, 120.50 etc.
• Strings of text e.g. "This text string" etc.
• Boolean e.g. true or false.
• JavaScript also defines two trivial data
types, null and undefined, each of which defines only a single value.
• In addition to these primitive data types, JavaScript supports a
composite data type known as object
Syntax:
• The console is a panel that displays important messages, like errors, for
developers.
• Much of the work the computer does with our code is invisible to us by default.
• If we want to see things appear on our screen, we can print, or log, to our console
directly.
• In JavaScript, the console keyword refers to an object, a collection of data and
actions, that we can use in our code.
• Keywords are words that are built into the JavaScript language, so the computer
will recognize them and treats them specially.
• One action, or method, that is built into the console object is the .log() method.
• When we write console.log() what we put inside the parentheses will get printed,
or logged, to the console.
Javascript Objects:
• Everything in javascript is an object.
• Objects are just data with properties and method.
• Properties are values associated with objects.
• Methods are actions that objects can perform.
• Javascript objects are classified into three categories.
• Built in objects
• Browser objects
• DOM objects
Built in Objects
• Javascript has several built in objects.
• These objects are accessible anywhere in the program.
• Array object
• Boolean object
• Number object
• String object
• Math object
• Date object
• RegExp object
Number Objects
• Numbers can be written with or without decimal.

var pi=3.14; // A number written with decimals


var x=34; // A number written without decimals
l><script>
lno=2;

lwhile (no!=Infinity)

l{

lno=no*no;

ldocument.write(no +'<BR>');

l}

</script>
• All of the properties available in number objects are read only .
• Their values remains the same.
• Five properties
• MAX_VALUE: returns the largest possible value in javascript.
• MIN_VALUE: returns the smallest number possible in javascript.
• NEGATIVE_INFINITY: represents largest negative number javascript can handle .
• Represented as –Infinity
• POSSITIVE_INFINITY: represents anything larger than MAX_VALUE and is
represented as infinity.
• NaN: represents a “Not a Number” value.
Number Methods:
• toExponential: Converts a number to Exponential notation.
• toFixed: formats a number with x numbers of digits after a
decimal point.
• toPrecision(x): determines the significant digits to display

based on argument passed.
• toString(x): returns the string representation of number’s

value.
• <!DOCTYPE html>
• <html>
• <body>
• <script>
• var x = 2/0;
• var y = -2/0;
• document.write(x + "<br>");
• document.write(y + "<br>");
• </script></body>
• </html>
toString method()
• <!DOCTYPE html>
• <html>
• <head> <script>
• function f1()
• {
• var num = 15;
• var a = num.toString();
• var b = num.toString(2); //base 2(binay)
• var c = num.toString(8);// base 8(octal)
• var d = num.toString(16);//base 16(hex)
• var n = a + "<br>" + b + "<br>" + c + "<br>" + d;
• var x = document.getElementById("abc");
• x.innerHTML=n;
• }
• </script></head>
• <body> <p id="abc"></p>
• <button onclick="f1()">Try it</button></body></html>
toPrecision() method
• <!DOCTYPE html>
• <html> <head> <script>
• function f1()
• {
• var num = new Number(13.3714);
• var n = num.toPrecision(2);
• var x = document.getElementById("abc");
• x.innerHTML=n
• }
• </script> </head> <body>
• <p id="abc"></p>
• <button onclick="f1()">Click Here</button>
• </body>
• </html>
Math Object
• The Math object allows you to perform mathematical tasks.
• All properties/methods of Math can be called by using Math
as an object, without creating it.
• The Math object includes several mathematical constants
and methods.

• Var pi_val=Math.PI;
• Var y=Math.sin(30);
• Var z= Math.sqrt(25);
Mathematical methods
Method Description
abs() Returns the absolute value of a number
acos() Returns the arccosine (in radians) of a number
asin() Returns the arcsine (in radians) of a number
atan() Returns the arctangent(in radians) of a number
ceil() Returns the smallest integer greater than or equal to a
number
floor() Returns the largest integer less than or equal to a number
pow() Returns base to the exponent power
round() Returns the value of a number rounded to the nearest
integer.
sqrt() Returns the square root of a number
random() Returns random number between 0 and 1.
Examples

• Math.random() //e.g. 0.63434343


• Math.floor(Math.random()) //returns random integer
between 0 and 10
• Math.round(25.9) //returns 26
• Math.round(25.2) //returns 25
• Math.round(-2.58) // returns -3
Mathematical constants
 JavaScriptprovides eight mathematical constants that can be accessed
from the Math object.
 Math.E - Returns Euler's number (approx. 2.718)
 Math.PI - Returns PI (approx. 3.14)
 Math.SQRT2 - Returns the square root of 2 (approx. 1.414)
 Math.SQRT1_2- Returns the square root of 1/2 (approx. 0.707)
 Math.LN2- Returns the natural logarithm of 2 (approx. 0.693)
 Math.LN10 - Returns the natural logarithm of 10 (approx. 2.302)
 Math.LOG2E - Returns the base-2 logarithm of E (approx. 1.442)
 Math.LOG10E- Returns the base-10 logarithm of E (approx. 0.434)
• <!DOCTYPE html>
• <html><head> <script>
• function f1()
• {
document.getElementById("demo").innerHTML=Math.max
(5,10);
• }
• </script></head>
• <body>
• <p id="demo"></p>
• <button onclick="f1()" value=”Try it”>
• </body>
• </html>
• <!DOCTYPE html>
• <html>
• <head> <script>
• function convert(degree)
• {
• if (degree=="C")
• {
• F=document.getElementById("c").value * 9 /
5 + 32;
• document.getElementById("f").value=Math.round(F);
• }
• else
• {
• C=(document.getElementById("f").value -32)
* 5 / 9;
• document.getElementById("c").value=Math.round(C);
• }
• }</script></head>
• <body>
• <form name=“f1”>
• <input id="c" name="c" onkeyup="convert('C')"> degrees
Celsius<br>
• equals<br>
• <input id="f" name="f" onkeyup="convert('F')"> degrees Fahrenheit
• </form>
• </body>
• </html>
• <!DOCTYPE html>
• <html>
• <head> <script>
• function f1()
• {
• var a=Math.abs(7.25);
• var b=Math.abs(-7.25);
• var c=Math.abs(null);
• var d=Math.abs("Hello");
• var e=Math.abs(2+3);
• var x=document.getElementById("abc");
• x.innerHTML=a + "<br>" + b + "<br>" + c + "<br>" + d + "<br>" + e;
• }
• </script> </head>
• <body> <p id="abc"></p>
• <button onclick="f1()">Click Here</button>
• </body></html>
Boolean Object
• The Boolean object represents two values: "true" or "false".
• The following code creates a Boolean object called myBoolean:

• var myBoolean=new Boolean();


• If the Boolean object has no initial value, or if the passed
value is one of the following:
• 0
• -0
• null
• ""
• false
• undefined
• NaN
Boolean Object
• the object is set to false.
• For any other value it is set to true (even with the
string "false")!
• <!DOCTYPE html>
• <html>
• <head>
• <script>
• var b1=new Boolean(0);
• var b2=new Boolean(1);
• var b3=new Boolean("");
• var b4=new Boolean(null);
• var b5=new Boolean(NaN);
• var b6=new Boolean("false");
• document.write("0 is boolean "+ b1 +"<br>");
• document.write("1 is boolean "+ b2 +"<br>");
• document.write("An empty string is boolean "+ b3 + "<br>");
• document.write("null is boolean "+ b4+ "<br>");
• document.write("NaN is boolean "+ b5 +"<br>");
• document.write("The string 'false' is boolean "+ b6 +"<br>");
• </head>
• <body></body></html>
String Object
• The String object is used to manipulate a stored piece
of text.
• String objects are created with new String().
• Syntax:

• var txt = new String("string");


• var txt = "string";
• A string simply stores a series of characters .
• A string can be any text inside quotes. You can use single or
double quotes:
• You can access each character in a string with its position
(index):
• Var str=“abc”;
• Var n=str[2];
• String indexes are zero-based, which means the first
character is [0], the second is [1], and so on.
• <!DOCTYPE html>
• <html>
• <body>
• <script>
• var var1=“Hello";
• var var2='Welcome';
• var answer1="It's alright";
• var answer2=“Welcome to ‘TSEC'";
• var answer3= ‘Welcome to “TSEC”’;
• document.write(var1 + "<br>")
• document.write(var2 + "<br>")
• document.write(answer1 + "<br>")
• document.write(answer2 + "<br>")
• document.write(answer3 + "<br>")
• </script></body></html>
Output
• Hello
• Welcome
• It's alright
• Welcome to ‘TSEC’
• Welcome to “TSEC”
String Length
• <!DOCTYPE html>
• <html>
• <body>
• <script>
• var txt = "Hello World!";
• document.write("<p>" + txt.length + "</p>");
• var txt="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
• document.write("<p>" + txt.length + "</p>");
• </script>
• </body>
• </html>
Output
• 12
• 26
Finding a String in a String

• The indexOf() method returns the position (as a number) of


the first found occurrence of a specified text inside a string
• The method returns -1 if the specified text is not found.
• The lastIndexOf() method starts searching at the end of the
string instead of at the beginning.
• <!DOCTYPE html>
• <html><body>
• <p id="p1">Always ask God to give you what you deserve, not what
you desire. Your desires may be a few, but you deserve a lot......
• </p>
• <p id="p2">0</p>
• <button onclick="myFunction()">Click Here</button>
• <script>
• function myFunction()
• {
• var str=document.getElementById("p1").innerHTML;
• var n=str.indexOf("God");
• document.getElementById("p2").innerHTML=n+1;
• }
• </script></body></html>
Always ask God to give you what you deserve, not what you
l

desire. Your desires may be a few, but you deserve a lot......

12

Click Here
Upper Case and Lower Case

A string is converted to upper/lower case with the


methods toUpperCase() / toLowerCase()
<!DOCTYPE html>
<html><body><script>
var txt="Hello World!";
document.write("<p>" + txt.toUpperCase() + "</p>");
document.write("<p>" + txt.toLowerCase() + "</p>");
document.write("<p>" + txt + "</p>");
</script>
<p>
The methods returns a new string.
The original string is not changed.
</p></body></html>
• HELLO WORLD!
• hello world!
• Hello World!
• The methods returns a new string. The original
string is not changed.
• <!DOCTYPE html>
• <html>
• <body>
• <p id="demo"></p>
• <button onclick="myFunction()">Try it</button>
• <script>
• function myFunction()
• {
• var str="a,b,c,d,e,f";
• var n=str.split(",");
• document.getElementById("demo").innerHTML=n[0];
• }</script></body></html>
Click the button to display the array values after the
l

split.
Try It
l a

Try It
String Properties and Methods

• Properties:
• length
• prototype
• constructor
• Methods:
• charAt()
• charCodeAt()
• concat()
• fromCharCode()
• indexOf()
• lastIndexOf()
• localeCompare()
• match()
• replace()
• search()
• slice()
• split()
• substr()
• substring()
• toLowerCase()
• toUpperCase()
• toString()
• trim()
• valueOf()
JavaScript Date Object
• The Date object is used to work with dates and times.
• Date objects are created with the Date() constructor.
• There are four ways of initiating a date:
• new Date() // current date and time
• new Date(milliseconds) //milliseconds since 1970/01/01
• new Date(dateString)
• new Date(year, month, day, hours, minutes, seconds,
milliseconds)
Set Dates

lWe can easily manipulate the date by using the methods available
for the Date object.
lAnd in the following example we set a Date object to be 5 days into

the future:
lvar myDate=new Date();

lmyDate.setDate(myDate.getDate()+5);
• <!DOCTYPE html>
• <html>
• <body>
• <script>
• var d=new Date();
• document.write(d);
• </script>
• </body>
• </html>

• o/p:Wed Feb 12 2014 02:03:48 GMT+0530 (India Standard Time)


• <!DOCTYPE html>
• <html>
• <head>
• <script>
• function startTime()
• {
• var today=new Date();
• var h=today.getHours();
• var m=today.getMinutes();
• var s=today.getSeconds();
• m=checkTime(m);
• s=checkTime(s);
• document.getElementById('txt').innerHTML=h+":"+m+":"+s;
• t=setTimeout(function(){startTime()},500);
• }
• function checkTime(i)
• {
• if (i<10)
• {
• i="0" + i;
• }
• return i;
• }
• </script></head>
• <body onload="startTime()">
• <div id="txt"></div></body></html>
What is an array?
An array is a special variable, which can hold more than one
value at a time.
var var1=“ABC";
An array can be created in three ways.
• Regular
• var var1=new Array();
• var1[0]=“hi";
• var1 [1]=“hello";
• var1 [2]=“welcome";

• Condensed:
• var var1=new Array(“hi”, “hello”, “welcome”);
• Literal:
• var var1=[“hi”, “hello”, “welcome”];
strcat
• <!DOCTYPE html>
• <html>
• <body><p id="demo"></p>
• <button onclick="f1()">Try it</button>
• <script>
• function f1()
• {
• var var1 = ["Jan", "Feb"];
• var var2 = ["Oct", "Nov", "Dec"];
• var var3 = var1.concat(var2);
• var x=document.getElementById("demo");
• x.innerHTML=var3;
• }
• </script></body></html>
Jan,Feb,Oct,Nov,Dec

Try It
• <!DOCTYPE html>
• <html>
• <body>
• <p id="demo"></p>
• <button onclick="f1()">Try it</button>
• <script>
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
• function f1()
• {
• fruits.reverse();
• var x=document.getElementById("demo");
• x.innerHTML=fruits;
• }</script></body></html>
Mango,Apple,Orange,Banana

Try It
• <!DOCTYPE html>
• <html><body>
• <p id="demo">Click the button to sort the array.</p>
• <button onclick=“f1()">Try it</button>
• <script>
• function f1()
• {
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
• fruits.sort();
• var x=document.getElementById("demo");
• x.innerHTML=fruits;
• }</script></body></html>
Apple,Banana,Mango,Orange

Try It
• <!DOCTYPE html> <html>
• <head><script>
• colors=new
Array("red","orange","green","blue","brown","purple","gray","whit
e");
• Index=0;
• function c1()
• {
• document.bgColor=colors[Index];
• Index=(Index+1)%colors.length;
• }
• function startc()
• {
• setInterval("c1()",3000);
• }
• function stopc()
• {
• window.document.write("Stopped");
• }
• window.onload=startc;
• </script>
• </head>
• <body>
• <form name="f1">
• <input type="button" value="Stop" onclick="stop();">
• </form></body></html>
RegExp
• What is RegExp?
• A regular expression is an object that describes a
pattern of characters.
• When you search in a text, you can use a pattern to
describe what you are searching for.
• A simple pattern can be one single character.
• A more complicated pattern can consist of more
characters, and can be used for parsing,
format checking, substitution and more.
• Regular expressions are used to perform powerful pattern-
matching and "search-and-replace" functions on text.

• Syntax
• var patt=new RegExp(pattern,modifiers);
• var patt=/pattern/modifiers;
• pattern specifies the pattern of an expression
• modifiers specify if a search should be global, case-sensitive,
etc.
• The i modifier is used to perform case-insensitive
matching.
• The g modifier is used to perform a global match (find
all matches rather than stopping after the first
match).
• var str=“Welcome to SE IT”
• var patt=/str/i;
• <!DOCTYPE html>
• <html>
• <head>
• <script>
• function f1()
• {
• var str = "Welcome to SE IT";
• var patt1 = /it/i;
• var result = str.match(patt1);
• document.getElementById("demo").innerHTML=result;
• }
• </script>
• </head>
• <body>
• <p id="demo"></p>
• <input type=”button” onclick="f1()" value=”Click Here”>
• </body>
• </html>
Using test()

lThe test() method is a RegExp expression method.


lIt searches a string for a pattern, and returns true or false, depending on

the result.
Method: test()
• searches a string for a specified value, and returns true or false,
depending on the result.

• <!DOCTYPE html>
• <html><head></head>
• <body><script>
• var str="Javascript is an intresting scripting language"
• var re=new RegExp("script","g");
• var result=re.test(str);
• document.write("Test 1 value:"+result);
• re= new RegExp("some","g");
• result=re.test(str);
• document.write("Test 2 value:"+result);
• </script>
• </body>
• </html>
• <html>
• <head>
• <noscript>
• <b> Javascript disable</b>
• </noscript>
• <script type="text/javascript">
• var dob = "12-10-1990";
• var ans = dob.split("-");
• alert(ans);
• alert(ans[0]);
• </script>
• </head>
• <body> </body>
• </html>
• <html> <head>
• <script type="text/javascript">
• function calculate()
• {
• var data = document.getElementById("txtdata").value;
• if(data.length==0)
• {
• alert("record missing");
• }
• else
• document.getElementById("result").innerHTML = data;
• }
• </script> </head>
• <body>
• <input type="text" id="txtdata" placeholder="enter record" />
<br />
• <input type="button" value="Enter" onclick="calculate()" />

• <h1 id="result">test data</h1> </body></html>


• <!doctype html><html> <head>
• <script type="text/javascript">
• function show(str)
• {
• var data = str.replace("thumb","main");
• var path = data+".jpg";
document.getElementById("main").innerHTML = "<img
src="+path+" />";
• </script>
• </head>
• <body>
• <div id="thumb">
• <img id="thumb-1" src="thumb-1.jpg“ onmouseover="show(this.id)" />

• <img id="thumb-2" src="thumb-2.jpg" onmouseover="show(this.id)" />

• <img id="thumb-3" src="thumb-3.jpg" onmouseover="show(this.id)" />


• </div>
• <div id="main">
• <img src="main-1.jpg" />
• </div>
• </body>
• </html>
Browser Object Model
• The Browser Object Model (BOM) is used to interact with the
browser.
• The default object of browser is window.
• You can call all the functions of window by specifying window or
directly.

window.alert("hello javatpoint");

alert("hello javatpoint")
1. Window object
• The window object represents a window in browser.
• An object of window is created automatically by the browser
Method Description

alert() displays the alert box containing message with ok button.


confirm() displays the confirm dialog box containing message with ok and
cancel button.
prompt() displays a dialog box to get input from the user.
open() opens the new window.
close() closes the current window.
setTimeout() performs action after specified time like calling function, evaluating
expressions etc.
• <script type="text/javascript"> • <script type="text/javascript">
• function f(){
• function f(){
• var v= confirm("Are u sure?");
• alert("Hello Alert Box"); • if(v==true){
• } • alert("ok");
• }
• </script>
• else{
• <input type="button" value="click" onclick=“f()"/> • alert("cancel");
• }

• }
• </script>

• <input type="button" value="delete record" onclick=“f()"/>
• Open() • <script type="text/javascript">
• function f(){
• <script type="text/javascript">
• setTimeout(
• function f(){ • function(){
• open("http://www.google.com"); • alert("Welcome")
• } • },2000);

• </script>
• }
• <input type="button" value=“click” on • </script>
click=“f()"/> •
• <input type="button" value="click" onclic
k=“f()"/>
2. History Object
• The JavaScript history object represents an array of URLs visited by
the user.
• By using this object, you can load previous, forward or any particular
page.
• Property of History object: length
• Methods:

1 forward loads the next page.


()
2 back() loads the previous page.
3 go() loads the given page number.
• history.back();//for previous page
• history.forward();//for next page
• history.go(2);//for next 2nd page
• history.go(-2);//for previous 2nd page
3. Navigator Object

The JavaScript navigator object is used for browser detection. It can be used to get
browser information such as appName, appCodeName, userAgent etc.
1.document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);
2.document.writeln("<br/>navigator.appName: "+navigator.appName);
3.document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);
4.document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);
5.document.writeln("<br/>navigator.language: "+navigator.language);
6.document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);
7.document.writeln("<br/>navigator.platform: "+navigator.platform);
8.document.writeln("<br/>navigator.onLine: "+navigator.onLine);

navigator.appCodeName: Mozilla
navigator.appName: Netscape
navigator.appVersion: 5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
navigator.cookieEnabled: true
navigator.language: en-US
navigator.userAgent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
navigator.platform: Win32
navigator.onLine: true
4. Screen Object
• The JavaScript screen object holds information of browser screen.
• It can be used to display screen width, height, colorDepth, pixelDepth
etc.
Document Object Model
• The document object represents the whole html document.
• When html document is loaded in the browser, it becomes a
document object.
• It is the root element that represents the html document.
• It has properties and methods.
• By the help of document object, we can add dynamic content to our
web page.
write("string") writes the given string on the doucment.

writeln("string") writes the given string on the doucment with newline character at the
end.

getElementById() returns the element having the given id value.

getElementsByName() returns all the elements having the given name value.

getElementsByTagName() returns all the elements having the given tag name.

getElementsByClassName() returns all the elements having the given class name.
• <script type="text/javascript">
• function printvalue(){
• var name=document.form1.name.value;
• alert("Welcome: "+name);
• }
• </script>

• <form name="form1">
• Enter Name:<input type="text" name="name"/>
• <input type="button" onclick="printvalue()" value="print name"/>
• </form>
• The document.getElementById() method returns the element of
specified id.
• The document.getElementsByName() method returns all the
element of specified name.
• The document.getElementsByTagName() method returns all the
element of specified tag name.
• <script type="text/javascript">
• function countpara(){
• var totalpara=document.getElementsByTagName("p");
• alert("total p tags are: "+totalpara.length);
• }
• </script>
• <p>This is a pragraph</p>
• <p>count total number of paragraphs</p>
• <p>Another Paragraph</p>
• <button onclick="countpara()">count paragraph</button>
innerHTML
• The innerHTML property can be used to write the dynamic html on
the html document.
• It is used mostly in the web pages to generate the dynamic html such
as registration form, comment form, links etc.
Javascript Events
• The change in the state of an object is known as an Event.
• In html, there are various events which represents that some activity
is performed by the user or by the browser.
• When javascript code is included in HTML, js react over these events
and allow the execution.
• This process of reacting over the events is called Event Handling.
• Thus, js handles the HTML events via Event Handlers.
Mouse Events Keyboard Events

onclick When mouse click on an element onkeydown & When the user press and
onkeyup then release the key
onmouse When the cursor of the mouse comes
over over the element
onmouse When the cursor of the mouse leaves
out an element
onmouse When the mouse button is pressed
down over the element
onmouse When the mouse button is released
up over the element
onmouse When the mouse movement takes
move place.
Form Events Window Events

onfocus When the user focuses on an onload When the browser finishes the loading
element of the page
onsubmit When the user submits the onunloa When the visitor leaves the current
form d webpage, the browser unloads it
onblur When the focus is away from a
form element onresize When the visitor resizes the window of
the browser
onchang When the user modifies or
e changes the value of a form
element
Form Validation
• 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 − 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.
• <html> <head> <title>Form Validation</title>
• <script type = "text/javascript">
• <select name = "Country">
• // Form validation code will come here.
• </script> </head> • <option value = "-1"
• <body> selected>[choose yours]</option>
• <form action = "" name = "myForm" onsubmit =
"return(validate());"> • <option value = "1">USA</option>
• <table cellspacing = "2" cellpadding = "2" border = "1"> • <option value = "2">UK</option>
• <tr> <td align = "right">Name</td>
• <td><input type = "text" name = "Name" /></td> • <option value = “3">INDIA</option>
• </tr> • </select> </td> </tr>
• <tr> <td align = "right">EMail</td>
• <td><input type = "text" name = "EMail" /></td>
• <tr>
• </tr> • <td align = "right"></td>
• <tr> <td align = "right">Zip Code</td>
• <td><input type = "text" name = "Zip" /></td>
• <td><input type = "submit"
• </tr>
value = "Submit" /></td>
• <tr> <td align = "right">Country</td> • </tr>
• <td>

• </table> </form>
• </body></html>
Data Format Validation
• <script type = "text/javascript">
• function validateEmail() {
• var emailID = document.myForm.EMail.value;
• atpos = emailID.indexOf("@");
• dotpos = emailID.lastIndexOf(".");

• if (atpos < 1 || ( dotpos - atpos < 2 )) {
• alert("Please enter correct email ID")
• document.myForm.EMail.focus() ;
• return false;
• }
• return( true );
• }
• </script>
Cookies
• In JavaScript, cookies are piece of data stored in the user's web
browser.
• The cookies are stored in the key-value pair inside the browser.
• We can manipulate the cookies using cookie property of document
object.
• We can set or store a cookie in key-value pair using the cookie
property.
• Web Browsers and Servers use HTTP protocol to communicate.
• HTTP is a stateless protocol. But for a commercial website, it is required to
maintain session information among different pages.
• For example, you have logged in to a particular website on a particular web
page. How do other webpages of the same website know your state that
you have already completed the logged-in process?
• In this case, cookies are used.
• Using cookies is the most efficient method of remembering and tracking
preferences, purchases, commissions, and other information required for
better visitor experience or site statistics.
• Your server sends some data to the visitor's browser in the form of a
cookie.
• The browser may accept the cookie.
• It is stored as a plain text record on the visitor's hard drive.
• Now, when the visitor arrives at another page on your site, the
browser sends the same cookie to the server for retrieval.
• Once retrieved, your server knows/remembers what was stored
earlier.
• Expires − The date the cookie will expire. If this is blank, the cookie will
expire when the visitor quits the browser.
• Domain − The domain name of your site.
• Path − The path to the directory or web page that set the cookie. This may
be blank if you want to retrieve the cookie from any directory or page.
• Secure − If this field contains the word "secure", then the cookie may only
be retrieved with a secure server. If this field is blank, no such restriction
exists.
• Name=Value − Cookies are set and retrieved in the form of key-value pairs
Setting Cookie:
• JavaScript can manipulate cookies using the cookie property of
the Document object.
• JavaScript can read, create, modify, and delete the cookies that apply
to the current web page.
• document.cookie = "key1 = value1;key2 = value2;expires = date";
Updating a cookie:
• To update the particular key-value pair in the cookie, you can assign
new key-value pair to the document.cookie property.
• document.cookie="key1=value1";
Deleting a cookie
• Sometimes you will want to delete a cookie so that subsequent
attempts to read the cookie return nothing.
• To do this, you just need to set the expiry date to a time in the past

You might also like