Chapter Four
Chapter Four
Informatics
Department of Information
Systems
CHAPTER FOUR
Course Title: Internet Programming
n D.
Client-Side
leg 2
: De
By Sc.)
sa
r u a rScripting Language
y ,2
3
rd
02
. b -
(M e: Fe oup:
t r
Da get G
Tar r r :-I 1
a e
Content
Introduction
Introduction to JavaScript
JavaScript Basics
• It is well-known for the development of web pages, many non-browser environments also use it. JavaScript can be used for Client-side
developments as well as Server-side developments.
• The programs in this language are called scripts. They can be written right in a web page’s HTML and run automatically as the page loads.
• Scripts are provided and executed as plain text. They don’t need special preparation or compilation to run.
• In this aspect, JavaScript is very different from another language called Java.
• JavaScript is not a compiled language, but it is a translated language. The JavaScript Translator (embedded in the browser) is responsible
for translating the JavaScript code for the web browser.
• It is complimentary to and integrated with Java. JavaScript is very easy to implement because it is integrated with HTML. It is open and
cross-platform.
• Today, JavaScript can execute not only in the browser, but also on the server, or actually on any device that has a special program called the
JavaScript engine.
Why to Learn JavaScript
• JavaScript is a must for students and working professionals to become a great Software Engineer specially
when they are working in Web Development Domain.
• JavaScript is the most popular programming language in the world and that makes it a programmer’s great choice.
Once you learnt JavaScript, it helps you developing great front-end as well as back-end software's using different
JavaScript based frameworks like jQuery, Node.JS etc.
• JavaScript is everywhere, it comes installed on every modern web browser and so to learn JavaScript you really do not
need any special environment setup.
• JavaScript usage has now extended to mobile app development, desktop app development, and game development.
This opens many opportunities for you as JavaScript Programmer.
• Due to high demand, there is tons of job growth and high pay for those who know JavaScript.
Features of JavaScript
• All popular web browsers support JavaScript as they provide built-in execution environments.
• JavaScript follows the syntax and structure of the C programming language. Thus, it is a structured
programming language.
• JavaScript is a weakly typed language, where certain types are implicitly cast (depending on the operation).
• JavaScript is an object-oriented programming language that uses prototypes rather than using classes for
inheritance.
• It is a case-sensitive language.
• Client-side validation,
• Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and
prompt dialog box),
• Syntax:
<script type="text/javascript">
</script>
• The document.write() function is used to display dynamic content through JavaScript./This simply
prints the specified text to the page.
• The text/ javascript is the content type that provides information to the browser about the data.
JavaScript Basics
• JavaScript in <body>
• In this example, a JavaScript function is placed in the <body> section of an HTML page.
<p id="demo"></p>
<script>
</script>
<script
</script>
• The innerHTML property can be used to write the dynamic html on the html document.
JavaScript Basics
<!DOCTYPE html>
<html>
<body>
<h2>Demo JavaScript in Body</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed."; }
</script>
</body>
</html>
JavaScript Basics
• JavaScript in <head>
• In this example, a JavaScript function is placed in the <head> section of an HTML page.
• The function is invoked (called) when a button is clicked:
• In next example, we are creating a function msg(). To create function in JavaScript, you need to
write function with function_name as given below.
• To call function, you need to work on event. Here we are using onclick event to call msg()
function.
<script type="text/javascript">
</script>
<html>
<body>
<h2>Demo External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>This example links to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>
<script src="myScript.js"></script>
</body>
</html>
JavaScript Basics
Whitespace and Line Breaks
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your
programs in a neat and consistent way that makes the code easy to read and understand.
For best readability, programmers often like to avoid code lines longer than 80 characters.
If a JavaScript statement does not fit on one line, the best place to break it is after an operator:
• JavaScript is a case-sensitive language. This means that the language keywords, variables, function names, and
any other identifiers must always be typed with a consistent capitalization of letters.
• So the identifiers Time and TIME will convey different meanings in JavaScript.
• NOTE − Care should be taken while writing variable and function names in JavaScript.
• The JavaScript comments are meaningful way to deliver message. It is used to add information about the code,
warnings or suggestions so that end user can easily interpret the code.
• The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.
• JavaScript Single line Comment
• It is represented by double forward slashes (//). It can be used before and after the statement.
• Any text between // and the end of the line will be ignored by JavaScript (will not be executed).
• JavaScript Multi line Comment
• Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
• It is represented by forward slash with asterisk then asterisk with forward slash.
• Multi-line comments start with /* and end with */.
JavaScript Display Possibilities
• JavaScript can "display" data in different ways:
• Using innerHTML
• The id attribute defines the HTML element. The innerHTML property defines the HTML content:
• document.getElementById("demo").innerHTML = 5 + 6;
• </script>
JavaScript Display Possibilities
• Using document.write()
document.write (5 + 6);
</script>
• Using window.alert()
• alert(5 + 6);
JavaScript Display Possibilities
• JavaScript Print
• The only exception is that you can call the window.print() method in the browser to print the content
of the current window.
• <button onclick="window.print()">Print this page</button>
Java script popup Box
• 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.
<script>confirm("do you want to proced!") </script>
• 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.
document.write("introduction to"+ x)
JavaScript Statements
• JavaScript Programs
• A computer program is a list of "instructions" to be "executed" by a computer.
• In a programming language, these programming instructions are called statements.
• A JavaScript program is a list of programming statements.
• JavaScript Statements
• JavaScript statements are composed of: Values, Operators, Expressions, Keywords, and Comments.
• This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo":
• <p id="demo"></p>
• <script>
• document.getElementById("demo").innerHTML = "Hello Dolly.";
• </script>
JavaScript Statements
• JavaScript Code Blocks
• JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
• The purpose of code blocks is to define statements to be executed together.
• One place you will find statements grouped together in blocks, is in JavaScript functions:
• <p id="demo1"></p>
• <p id="demo2"></p>
• <button type="button" onclick="myFunction()">Try it</button>
• <script>
• function myFunction() {
• document.getElementById("demo1").innerHTML = "Hello Dolly!";
• document.getElementById("demo2").innerHTML = "How are you?";
• }
• </script>
JavaScript Statements
• JavaScript Keywords
• JavaScript statements often start with a keyword to identify the JavaScript action to be performed.
• Here is a list of some of the keywords you will learn about in this tutorial:
JavaScript Variable
• One of the most fundamental characteristics of a programming language is the set of data types it supports. These
are the type of values that can be represented and manipulated in a programming language.
• Note :- JavaScript does not make a distinction between integer values and floating-point values. All numbers in
JavaScript are represented as floating-point values.
• Like many other programming languages, JavaScript has variables. Variables can be thought of as named
containers. You can place data into these containers and then refer to the data simply by naming the container.
• Before you use a variable in a JavaScript program, you must declare it.
JavaScript Variable
• Variables are declared with the var, let and const keyword as follows.
• You can also declare multiple variables with the same var keyword as follows:- var money, name;
• Storing a value in a variable is called variable initialization. You can do variable initialization at the time of
variable creation or at a later point in time when you need that variable.
• For instance, you might create a variable named money and assign the value 2000.50 to it later. For another
variable, you can assign a value at the time of initialization as follows.
var money;
money = 2000.50;
• Note − Use the var keyword only for declaration or initialization, once for the life of any variable name in a
document. You should not re-declare same variable twice.
JavaScript Variable
• JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type.
• Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of value the
variable will hold.
• The value type of a variable can change during the execution of a program and JavaScript takes care of it
automatically.
<p id="demo"></p>
<script>
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
</script>
JavaScript Variable
• All JavaScript variables must be identified with unique names.
• Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
• The general rules for constructing names for variables (unique identifiers) are:
• After first letter we can use digits (0 to 9), for example value1
JavaScript Variable
• One Statement, Many Variables
• Start the statement with var and separate the variables by comma:
• Value = undefined
• In computer programs, variables are often declared without a value. The value can be something that has to be
calculated, or something that will be provided later, like user input.
• The variable carName will have the value undefined after the execution of this statement: var carname;
JavaScript Variable
• JavaScript Variables are Dynamically Typed
After the execution of the 1st statement, the data type
of the variable “sum” is “undefined”
• The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two
scopes.
• Global Variables − A global variable has global scope which means it can be defined anywhere in your
JavaScript code. Or A variable i.e. declared outside the function or declared with window object is known as
global variable.
• Local Variables − A local variable will be visible only within a function where it is defined. Function parameters
are always local to that function. Or A JavaScript local variable is declared inside block or function. It is
accessible within the function or block only.
• Within the body of a function, a local variable takes precedence over a global variable with the same name. If you
declare a local variable or function parameter with the same name as a global variable, you effectively hide the
global variable.
JavaScript Variable
<script> function checkscope( ) {
document.write(myVar); } </script>
function a(){
document.writeln(data); }
function b(){
document.writeln(data); }
b(); </script>
JavaScript Variable
Example
<script>
var s1=12;
var s2=28;
sum=s1+s2
fark=s1-s2
carp=s1*s2
bol=s1/s2
document.write("<br>sum<br>") HTML written
document.write("<br>the sum will be: "+sum) inside JavaScript
document.write("<br>subtraction: "+fark)
document.write("<br>the result: "+carp)
document.write("<br>the result is: "+bol)
alert(" practice!")
</script >
JavaScript Variable
• Write JavaScript code that accept two numbers from the user and display their sum
<SCRIPT TYPE="text/javascript">
var firstNumber, // first string entered by user
secondNumber, // second string entered by user
number1, // first number to add The prompt() method is used to display a dialog
number2, // second number to add with an optional message prompting the user to
sum; // sum of number1 and number2
input some text. It is often used if the user wants
// read in first number from user as a string
to input a value before entering a page. It returns
firstNumber = prompt("Enter first integer" );
// read in second number from user as a string a string containing the text entered by the user,
secondNumber = prompt( "Enter second integer" ); or null.
// convert numbers from strings to integers The parseInt() function parses a string argument
number1 = parseInt(firstNumber);
and returns an integer of the specified radix (the
number2 = parseInt( secondNumber );
base in mathematical numeral systems).
// add the numbers
sum = number1 + number2; // display the results execute
document.write( "<H1>The sum is " + sum + "</H1>" );-->
Reading assignments
• Operators
Arithmetic, comparison, logical,
Bitwise, Assignments
• Conditional statement
If, if….else, if…else..if and
switch
• Loop
While loop, do..while loop
and for loop
• Expression in JavaScript
• The difference between expression and statement
Array in JavaScript
• The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential collection of
elements of the same type.
• An array is used to store a collection of data, but it is often more useful to think of an array as a collection of
variables of the same type.
• By array literal
• var arrayname=[value1,value2.....valueN];
• As you can see, values are contained inside [ ] and separated by , (comma).
Array in JavaScript
<script>
With JavaScript, the full array can be accessed
Var i; by referring to the array name:
var emp=["Sonoo","Vimal","Ratan"]; <p id="demo"></p>
<script>
for (i=0;i<emp.length;i++){ var cars = ["Saab", "Volvo", "BMW"];
] + "<br/>"); document.getElementById("demo").innerHTML
= cars;
} </script> document.write(emp[i </script>
The .length property returns the length of an array.
or Returns the number of elements <script>
var i;
JavaScript Array directly (new keyword) var emp = new Array();
The syntax of creating array directly is given below: emp[0] = "Arun";
emp[1] = "Varun";
var arrayname=new Array(); emp[2] = "John";
Here, new keyword is used to create instance of array. for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
Let's see the example of creating array directly.
}
The Array() constructor is used to create Array objects. </script>
The new keyword constructs and returns an object (instance) of a constructor Array.
Array in JavaScript
You can also create an array, and then provide the elements:
<p id="demo"></p>
<script>
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
document.getElementById("demo").innerHTML = cars; </script>
You access an array element by referring to the index number:
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script> //Note: Array indexes start with 0.
JavaScript array elements are accesses using numeric indexes (starting from 0).
Array in JavaScript
Changing an Array Element
This statement changes the value of the first element in cars.
<p>JavaScript array elements are accessed using numeric indexes (starting from 0).</p>
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
document.getElementById("demo").innerHTML = cars;
</script>
The length property of an array returns the length of an array (the number of array elements).
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.length; </script>
Note: The length property is always one more than the highest array index.
Array in JavaScript
Accessing the Last Array Element
<p>JavaScript array elements are accesses using numeric indexes (starting from 0).</p>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits[fruits.length-1];
</script>
Adding Array Elements
The easiest way to add a new element to an array is using the push() method:
Before we use a function, we need to define it. The most common way to define a function in JavaScript is by using
the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a
statement block surrounded by curly braces.
The basic syntax is shown here. <script>
You can pass less or more arguments while calling a function. If you pass less arguments then rest of the parameters
will be undefined. If you pass more arguments then additional arguments will be ignored.
<script> function ShowMessage(firstName, lastName)//// declaring a function
{ alert("Hello " + firstName + " " + lastName);}
In the above program, the ShowMessage
ShowMessage("Steve", "Jobs", "Mr."); //calling function
function is declared with a two parameter.
ShowMessage("Bill");
Then when the function is called, an
ShowMessage(); </script>
argument is passed into the function.
Function in JavaScript
Function return
We can call function that returns a value and use it in our program.
The return statement can be used to return the value to a function call.
The return statement denotes that the function has ended. Any code after return is not executed.
If nothing is returned, the function returns an undefined value.
// program to add two numbers
Let’s see the example of function that returns value. // declaring a function
Onclick Event Type: This is the most frequently used event type which occurs when a user clicks the left button of
his mouse. You can put your validation, warning etc., against this event type.
<script>
function sayHello() {
It allows the programmer to execute a JavaScript's function when an element gets clicked.
Event in JavaScript
Example on onclick event
<h2>JavaScript HTML Events</h2>
<p>Click the button to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
Event in JavaScript
onsubmit is an event that occurs when you try to submit a form. You can put your form validation against
this event type.
The following example shows how to use onsubmit. Here we are calling a validate() function before
submitting a form data to the webserver.
If validate() function returns true, the form will be submitted, otherwise it will not submit the data.
function validation()
{
all validation goes here
.........
return either true or false
}
<form method="POST" action=“yes.php" onsubmit="return validate()"> </form>
.......
<input type="submit" value="Submit" />
Event in JavaScript
onmouseover and onmouseout
These two event types will help you create nice effects with images or even with text as well. The onmouseover
event triggers/activates when you bring your mouse over any element and the onmouseout triggers when you move
your mouse out from that element.
Try the following example
<script type="text/javascript"> function over() {
document.write ("Mouse Over"); }
function out() {
document.write ("Mouse Out");
}
</script>
<div onmouseover="over()" >
<h2> This is inside the division <h2> </div>
Event in JavaScript
The onkeydown event occurs when the user is pressing a key (on the keyboard).
<p>A function is triggered when the user is pressing a key in the input field.</p>
<input type="text" onkeydown="myFunction()">
<script>
function myFunction()
{
alert("You pressed a key inside the input field");
}
</script>
Event in JavaScript
The onload event occurs when an object has been loaded.
onload is most often used within the <body> element to execute a script once a web page has completely loaded all
content (including images, script files, CSS files, etc.).
The onload event can be used to check the visitor's browser type and browser version, and load the proper version
of the web page based on the information.
The onload event can also be used to deal with cookies (see "More Examples" below).
<body onload="myFunction()">
<h1>Hello World!</h1>
<script>
function myFunction() {
alert("Page is loaded");
} </script>
Errors & Exceptions Handling
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors.
Syntax Errors
These are errors that cannot be interpreted by the computer. These errors stop the program from working.
Spelling errors (wrong spelling such as fiction instead of function).
The omission of important characters, such as not using a semicolon to end a statement.
For example, the following line causes a syntax error because it is missing a closing parenthesis.
<script type = "text/javascript">
<!--
window.print(;
//-->
</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.
Errors & Exceptions Handling
Runtime Errors
Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).
The errors get detected when your program runs. It crashes or raises an exception. Thus, exception
handlers handle exception errors.
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.
window.printme(); //-->
</script>
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue
normal execution.
Errors & Exceptions Handling
Logical Errors
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.
Errors & Exceptions Handling
• With the use of exceptions, you can responsibly manage some of these problems we face as
developers.
• Exception handling is the process of converting a code error message into a user-friendly error
message. It is a necessary step in the development process.
• Exception handling is one of the powerful JavaScript features to handle errors and maintain a regular
JavaScript code/program flow.
• Errors can be coding errors made by the programmer, errors due to wrong input, and other
unforeseeable things.
Errors & Exceptions Handling
try_statements
• The statements to be executed. Or The try statement defines a code block to run (to try).
catch_statements
• Statement that is executed if an exception is thrown in the try-block. Or The catch statement defines a
code block to handle any error.
exception_var
• An optional identifier to hold an exception object for the associated catch-block.
• The try statement consists of a try-block, which contains one or more statements. {} must always be
used, even for single statements. A catch-block, a finally-block, or both must be present. This gives us
three forms for the try statement:
• Here, the code which needs possible error testing is kept within the try block. In case any error occur,
it passes to the catch{} block for taking suitable actions and handle the error. Otherwise, it executes the
Errors & Exceptions Handling
• Catch{} statement: This block handles the error of the code by executing the set of statements written
within the block.
• This block contains either the user-defined exception handler or the built-in handler. This block executes
only when any error-prone code needs to be handled in the try block. Otherwise, the catch block is
skipped.
try {
Block of code to try
}
catch(err) {
Block of code to handle errors }
• Catch {} statement executes only after the execution of the try {} statement. Also, one try block can
contain one or more catch blocks.
Errors & Exceptions Handling
<p id="demo"></p>
<script> In this example we misspelled "alert" as "adddlert"
to deliberately produce an error:
try {
JavaScript catches adddlert as an error, and executes
adddlert("Welcome guest!"); } the catch code to handle it.
catch(err)
{
document.getElementById("demo").innerHTML = err.message; }
</script>
When an exception occurs in the try block, the exception is placed in err and the catch block is executed. The
optional finally block executes unconditionally after try/catch.
The message property sets or returns an error message.
Syntax:- errorObj.message
Error object, finally statement , throw statement , error name values and built-in handler?????
Errors & Exceptions Handling
<script>
try{
document.write(b); //b is undefined but still trying to fetch its value. Thus catch block will
be invoked
}catch(e)
</script>
Document Object Model
• JavaScript can access all the elements in a webpage making use of Document Object Model (DOM).
• In fact, the web browser creates a DOM of the webpage when the page is loaded. 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.
• According to W3C - "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.“
Methods of document object: We can access and change the contents of document by its methods.
• The important methods of document object are as follows:
Document Object Model
• Accessing field value by document object. If you want to access any element in an HTML page, you always start
with accessing the document object.
• In this example, we are going to get the value of input text by user. Here, we are using
document.form1.name.value to get the value of name field.
• Here, document is the root element that represents the html document.
• form1 is the name of the form.
• name is the attribute name of the input text.
• value is the property, that returns the value of the input text.
• Let's see the simple example of document object that prints name with welcome message.
<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>
Document Object Model
• The document.getElementById() method returns the element of specified id.
• In the previous page, we have used document.form1.name.value to get the value of the input value. Instead of this,
we can use document.getElementById() method to get value of the input text. But we need to define id for the
input field.
• Let's see the simple example of document.getElementById() method that prints cube of the given number.
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number); }
</script> <form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
Document Object Model
• The document.getElementsByName() method returns all the element of specified name.
• The syntax of the getElementsByName() method is given below:
• document.getElementsByName("name") . Here, name is required.
• Example of document.getElementsByName() method
• In this example, we going to count total number of genders.
• Here, we are using getElementsByName() method to get all the genders.
<script type="text/javascript">
function totalelements() {
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length); } </script> <form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
<input type="button" onclick="totalelements()" value="Total Genders">
</form>
Document Object Model
• The document.getElementsByTagName() method returns all the element of specified tag name.
• The syntax of the getElementsByTagName() method is given below:
• In this example, we going to count total number of paragraphs used in the document. To do this, we have called the
document.getElementsByTagName("p") method that returns the total paragraphs.
<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>Here we are going to count total number of paragraphs by getElementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
Document Object Model
• In this example, we going to count total number of h2 and h3 tags used in the document.
<script type="text/javascript"> function counth2(){
var totalh2=document.getElementsByTagName("h2");
alert("total h2 tags are: "+totalh2.length); }
function counth3(){
var totalh3=document.getElementsByTagName("h3");
alert("total h3 tags are: "+totalh3.length); } </script>
<h2>This is h2 tag</h2>
<h2>This is h2 tag</h2>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<button onclick="counth2()">count h2</button>
<button onclick="counth3()">count h3</button>
JS innerHTML property???
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.
• 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.
• During input form processing, we have to check the data validation of a specific fields. Data validation is the
process of ensuring that user input is clean, correct, and useful.
• Typical validation tasks can be: has the user filled in all required fields? has the user entered text in a numeric
field?
• Most often, the purpose of data validation is to ensure correct user input.
• Server side validation is performed by a web server, after input has been sent to the server.
• Client side validation is performed by a web browser, before input is sent to a web server.
Form Validation
• 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.
• JavaScript provides facility to validate the form on the client-side so data processing will be faster than server-
side validation. Most of the web developers prefer JavaScript form validation.
• In this example, we are going to validate the name and password. The name can’t be empty and password can’t be
less than 6 characters long.
• Here, we are validating the form on form submit. The user will not be forwarded to the next page until given
values are correct.
Form Validation
function validateform(){
var name=document.myform.name.value; var password=document.myform.password.value; if (name==null ||
name==""){ alert("Name can't be blank"); return false;
} else if(password.length<6) { alert("Password must be at least 6 characters long.");
return false; } } </script>
<body> <form name="myform" method="post" action=“del.php" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
• When a user clicks on submit clickable button of a form, JavaScript onsubmit event will call a function.
• In our example, we call validateform() function on form submission.
• That will first validate the form fields and will return a boolean value either true or false. Depending upon the
returned value the form will submit if it will be true.
• The return statement ends function execution and specifies a value to be returned to the function caller.
• When a return false statement is called in a function, the execution of this function is stopped.
Form Validation
JavaScript Retype Password Validation
var secondpassword=document.f1.password2.value;
</script>
<input type="submit">
</form>
Form Validation
JavaScript Number Validation
Let's validate the textfield for numeric value only. Here, we are using isNaN() function.
</script>
</form>
Form Validation
JavaScript email validation
There are many criteria that need to be follow to validate the email id such as:
function validateForm() {
return false; }}
</form>
Form Validation
JavaScript is often used to validate numeric input:
<p>Please input a number between 1 and 10:</p>
<input id="numb">
<p id="demo"></p><script>
function myFunction() { // Get the value of the input field with id="numb"
• When a web server has sent a web page to a browser, the connection is shut down, and the server
forgets everything about the user.
• Cookies were invented to solve the problem "how to remember information about the user":
• When a user visits a web page, his/her name can be stored in a cookie.
• Next time the user visits the page, the cookie "remembers" his/her name.
• A cookie contains the information as a string generally in the form of a name-value pair separated by
semi-colons.
• It maintains the state of a user and remembers the user's information among all the web pages.
Java Script Cookies
• A cookie is a piece of data that is stored on your computer to be accessed by your browser. You also might have
enjoyed the benefits of cookies knowingly or unknowingly.
• Have you ever saved your Facebook password so that you do not have to type it each and every time you try to
login? If yes, then you are using cookies. Cookies are saved as key/value pairs.
• A cookie is a small file with the maximum size of 4KB that the web server stores on the client computer.
• Once a cookie has been set, all page requests that follow return the cookie name and value. A cookie can only be
read from the domain that it has been issued from.
• The communication between a web browser and server happens using a stateless protocol named HTTP. Stateless
protocol treats each request independent. So, the server does not keep the data after sending it to the browser.
But in many situations, the data will be required again. Here come cookies into a picture. With cookies, the web
browser will not have to communicate with the server each time the data is required. Instead, it can be fetched
directly from the computer.
Java Script Cookies
How Cookies Works?
• When a user sends a request to the server, then each of that request is treated as a new request sent by the different
user.
• So, to recognize the old user, we need to add the cookie with the response from the server. browser at the client-side.
• Now, whenever a user sends a request to the server, the cookie is added with that request automatically. Due to the
cookie, the server recognizes the users.
• Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie.
• If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page
on your site, the browser sends the same cookie to the server for retrieval.
• Name=Value − Cookies are set and retrieved in the form of key-value pairs
• JavaScript provides some optional attributes that enhance the functionality of cookies. Here, is the list of some
attributes with their description
• Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits/close the
browser. It maintains the state of the cookie up to the specified date and times.
• 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. It expands the scope of the cookie to the all pages of a website.
• By default cookies are valid only for web pages in the directory of the current web page that stored them.as well as
its descendants. If you want a cookie that is valid across all your page in your web site, then set the path attribute to
the root of your web site.
Java Script Cookies
How to create and read a Cookie in JavaScript?
• JavaScript can also manipulate cookies using the cookie property of the Document object. .
• The following syntax is used to create a cookie: document.cookie="name=value";
• Let's see an example to set and get a cookie. <input type="button" value="setCookie"
• Reading a cookie & writing is just as simple , because the onclick="setCookie()">
<input type="button" value="getCookie"
value of the document.cookie object is the cookie. onclick="getCookie()">
<script>
• So you can use this string whenever you want to access/write
function setCookie() {
the cookie. The document.cookie string will keep a list of document.cookie="color=red"; }
function getCookie() {
name=value pairs separated by semicolons, where name is the if(document.cookie.length!=0) {
name of a cookie and value is its string value. var
array=document.cookie.split("=");
• You can use strings' split() function to break a string into key alert("Name="+array[0]+"
and values. "+"Value="+array[1]); } else
{
alert("Cookie not available"); } }
</script>
Java Script Cookies
• if you want a cookie that is valid across all your page in your web site, then set the path attribute to the root of your
web site. Example:
• With out path attribute: if you create your cookie at localhost/cookie/parentcookie.html then
http://localhost/cookies/child/child.html
• The display property also allows the author to show or hide an element. However, if you set display:none, it
hides the entire element or Element will not be displayed if display value is none.
Hiding Fields using Java Script
The onchange event occurs when the value of an element has been changed. When the user modifies or changes
the value of a form element.
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
</script>
Hiding Fields using Java Script
IN HTML: <element onchange="myScript">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
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.
For example, when a user clicks over the browser, add js code, which will execute the task to be performed on the
event.
JavaScript Events Summary
JavaScript Events Summary
Recommendation to……..
• jQuery is a JavaScript library designed to simplify HTML DOM tree traversal
and manipulation, as well as event handling, CSS animation, and Ajax.