JAVA SCRIPT
CONTENTS
Basics of JavaScript
JS- Home
JS- Introduction
JS- JavaScript History
JS- Features of JavaScript
JS- Uses of JavaScript
JS- JavaScript Comment
JS- First Program
Programming Basics
JS- Where Use JavaScript
JS- Variable Declaration
JS- Sum of Numbers
JS- Factorial of Numbers
JS- If Statement
JS- Looping Statement
JS- Switch Statement
JS- Function
JS- Array
Advance JavaScript
JS- Dialog Box
JS- Window Object
JS- Document Object
JS- Event
JS- getElementById
JavaScript Validation
JS- Forms Validation
JS- Email Validation
JS- Password Validation
JS- Re-Password Validation
2
JavaScript
JavaScript is a object-based scripting language. It is light weighted. Using HTML we
can only design a web page but you can not run any logic on web browser like
addition of two numbers, check any condition, looping statements (for, while),
decision making statement (if-else) at client side. All these are not possible using
HTML so for perform all these task at client side you need to use JavaScript.
Born JavaScript
It is first implemented by Netscape (with help from Sun Microsystems). JavaScript
was created by Brendan Eich at Netscape in 1995 for the purpose of allowing code
in WebPages
Prerequisites
Before learning of JavaScript you must be basic knowledge of C Language (mainly
looping and conditional statements concept), and also knowledge of Html.
Knowledge of looping and conditional statements concept in C language is required
because JavaScript is used for perform logical operation of client side.
Introduction
JavaScript is a object-based scripting language and it is light weighted. It is first
implemented by Netscape (with help from Sun Microsystems). JavaScript was
created by Brendan Eich at Netscape in 1995 for the purpose of allowing code in
web-pages (performing logical operation on client side).
It is not compiled but translated. JavaScript Translator is responsible to translate the
JavaScript code which is embedded in browser.
Netscape first introduced a JavaScript interpreter in Navigator 2. The interpreter was
an extra software component in the browser that was capable of interpreting
JavaScript source code inside an HTML document. This means that web page
developer no need other software other than a text editor of develop any web page.
Why we Use JavaScript?
Using HTML we can only design a web page but you can not run any logic on web
browser like addition of two numbers, check any condition, looping statements (for,
while), decision making statement (if-else) at client side. All these are not possible
using HTML so for perform all these task at client side you need to use JavaScript.
Where it is used?
It is used to create interactive websites. It is mainly used for:
Client-side validation
Dynamic drop-down menus
Displaying data and time
Build small but complete client side programs .
Displaying popup windows and dialog boxes (like alert dialog box,
confirm dialog box and prompt dialog box)
Displaying clocks etc.
History
JavaScript is a object-based scripting language and it is light weighted. It is first
implemented by Netscape (with help from Sun Microsystems). JavaScript was
created by Brendan Eich at Netscape in 1995 for the purpose of allowing code in
web-pages (performing logical operation on client side).
Using HTML we can only design a web page but you can not run any logic on web
browser like addition of two numbers, check any condition, looping statements(for,
while), decision making statement(if-else) etc. All these are not possible using HTML
so for perform all these task we use JavaScript.
Using HTML we can only design a web page if we want to run any programs like c
programming we use JavaScript. Suppose we want to print sum of two number then
we use JavaScript for coding.
Features of JavaScript
JavaScript is a client side technology, it is mainly used for gives client side validation,
but it have lot of features which are given below;
JavaScript is a object-based scripting language.
Giving the user more control over the browser.
It Handling dates and time.
It Detecting the user's browser and OS,
It is light weighted.
JavaScript is a scripting language and it is not java.
JavaScript is interpreter based scripting language.
JavaScript is case sensitive.
JavaScript is object based language as it provides predefined objects.
Every statement in JavaScript must be terminated with semicolon (;).
Most of the JavaScript control statements syntax is same as syntax of control
statements in C language.
An important part of JavaScript is the ability to create new functions within
scripts. Declare a function in JavaScript using function keyword.
Uses of JavaScript
There are too many web applications running on the web that are using JavaScript
technology like gmail, facebook,twitter, Google map, youtube etc.
Uses of JavaScript
Client-side validation
Dynamic drop-down menus
Displaying data and time
Validate user input in an HTML form before sending the data to a server.
Build forms that respond to user input without accessing a server.
Change the appearance of HTML documents and dynamically write HTML
into separate Windows.
Open and close new windows or frames.
Manipulate HTML "layers" including hiding, moving, and allowing the user to
drag them around a browser window.
Build small but complete client side programs .
Displaying popup windows and dialog boxes (like alert dialog box, confirm
dialog box and prompt dialog box)
Displaying clocks etc.
Comment
Comment is nothing but it is a statement which is not display on browser window. it is
useful to understand the which code is written for what purpose.
Comments are useful in every programming language to deliver message. It is used
to add information about the code, warnings or suggestions so that the end user or
other developer can easily interpret the code.
Types of JavaScript Comments
There are two types of comments are in JavaScript
Single-line Comment
Multi-line Comment
Single-line Comment
It is represented by double forward slashes (//). It can be used before any statement.
Example
<script>
// It is single line comment
document.write("Hello JavaScript");
</script>
Result
Hello JavaScript
Multi-line Comment
It
can
be
used
to
add
single
as
well
as
multi
line
comments.
It is represented by forward slash (/) with asterisk (*) then asterisk with forward slash.
Example
<script>
/* It is multi line comment.
It will not be displayed */
document.write("JavaScript multiline comment");
</script>
Result
JavaScript multiline comment
JavaScript First Program
JavaScript simple example to verify age of any person, if age is greater than 18 show
message adult otherwise show under 18
JavaScript Example to verify age
Example
<html>
<head>
<script>
function verify(){
var no;
no=Number(document.getElementById("age").value);
if(no<18)
{
alert("Under 18");
}
else
{
alert("You are Adult");
}
}
</script>
</head>
<body>
Enter your age:<input id="age"><br />
<button onclick="verify()">Click me</button>
</body>
</html>
Result
Enter your age:
Click me
Way of Using JavaScript
There are three places to put the JavaScript code.
Between the <body> </body> tag of html (Inline JavaScript)
Between the <head> </head> tag of html (Internal JavaScript)
In .js file (External JavaScript)
Inline JavaScript
When java script was written within the html element using attributes related to
events of the element then it is called as inline java script.
Example of Inline JavaScript
Example
<html>
<form>
<input type="button" value="Click" onclick="alert('Button Clicked')"/>
</form>
</html>
Result
Internal JavaScript
When java script was written within the section using element then it is called as
internal java script.
Example of Internal
JavaScript
Example
<html>
<head>
<script>
function msg()
{
alert("Welcome in JavaScript");
}
</script>
</head>
<form>
<input type="button" value="Click" onclick="msg()"/>
</form>
</html>
Result
External JavaScript
Writing java script in a separate file with extension .js is called as external java script.
For adding the reference of an external java script file to your html page, use tag with
src attribute as follows
Example
<script type="text/JavaScript" src="filename.js"/>
Create a file with name functions.js and write the following java script functions in it.
message.js
Example
function msg()
{
alert("Hello Javatpoint");
}
Create a html page and use the file functions.js as follows
index.html
Example
<html>
10
<head>
<script type="text/JavaScript" src="message.js"></script>
</head>
<body>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Variable Declaration
Java script did not provide any data types for declaring variables and a variable in
java script can store any type of value. Hence java script is loosely typed language.
We can use a variable directly without declaring it.
Only var keyword are use before variable name to declare any variable.
Syntax
var x;
Rules to declaring a variable
Name must start with a letter (a to z or A to Z), underscore( _ ), or
dollar( $ ) sign.
After first letter we can use digits (0 to 9), for example value1.
JavaScript variables are case sensitive, for example x and X are different
variables.
Variable declaration
Example
var x = 10; // Valid
var _value="porter"; // Valid
var 123=20; // Invalid
var #a=220; // Invalid
11
var *b=220; // Invalid
Example of Variable declaration in JavaScript
Example
<script>
var a=10;
var b=20;
var c=a+b;
document.write(c);
</script>
Output
30
Types of Variable in JavaScript
Local Variable
Global Variable
Local Variable
A variable which is declared inside block or function is called local variable. It is
accessible within the function or block only. For example:
Example
<script>
function abc()
{
var x=10; //local variable
}
</script>
or
Example
<script>
If(10<13)
12
{
var y=20;//javascript local variable
}
</script>
Global Variable
A global variable is accessible from any function. A variable i.e. declared outside the
function or declared with window object is known as global variable. For example:
Syntax
<script>
var value=10;//global variable
function a()
{
alert(value);
}
function b()
{
alert(value);
}
</script>
Declaring global variable through window object
The best way to declare global variable in JavaScript is through the window object.
For example:
Syntax
window.value=20;
Now it can be declared inside any function and can be accessed from any function.
For example:
Example
13
function m()
{
window.value=200; //declaring global variable by window object
}
function n()
{
alert(window.value); //accessing global variable from other function
}
Example of JavaScript
Here i will show you how to write you first JavaScript code, you only need to write
your JavaScript code inside <script> ..... </script> tag using any editor like notepad or
edit plus. Save below code with .html or .htm extension. No need to compile
your JavaScript code just open your code in any web browser.
Find sum of two number using JavaScript
Example
<!doctype html>
<html>
<head>
<script>
function add(){
var a,b,c;
a=Number(document.getElementById("first").value);
b=Number(document.getElementById("second").value);
c= a + b;
document.getElementById("answer").value= c;
}
</script>
</head>
<body>
<input id="first">
<input id="second">
<button onclick="add()">Add</button>
<input id="answer">
</body>
14
</html>
Result
Enter First Number:
Enter Second Number:
Add
Code Explanation
no=Number(document.getElementById("first").value);
This code is used for receive first input value form input field which
have id first.
no=Number(document.getElementById("second").value);
This code is used for receive first input value form input field which
have id second.
document.getElementById("answer").value= fact;
This code is used for receive calculated value of factorial and display in
input field which have id answer
<button onclick="add()">Add</button>
This code is used for call add function when button clicked.
Factorial of number
Using JavaScript you can find factorial of any number, here same logic are applied
like c language
you only need to write your JavaScript code inside <script> ..... </script> tag using
any editor like notepad or edit plus. Save below code with .html or .htm extension. No
need to compile yourjavascript code just open your code in any web browser.
Find factorial of number using JavaScript
Example Factorial of any number
<!doctype html>
<html>
<head>
<script>
15
function show(){
var i, no, fact;
fact=1;
no=Number(document.getElementById("num").value);
for(i=1; i<=no; i++)
{
fact= fact*i;
}
document.getElementById("answer").value= fact;
}
</script>
</head>
<body>
Enter Num: <input id="num">
<button onclick="show()">Factorial</button>
<input id="answer">
</body>
</html>
Result
Enter Num:
Factorial
Code Explanation
no=Number(document.getElementById("num").value);
This code is used for receive input value form input field which have id
num.
document.getElementById("answer").value= fact;
This code is used for receive calculated value of factorial and display in
input field which have id answer
<button onclick="show()">Factorial</button>
This code is used for call show function when button clicked.
If else Statement
16
The if statement is used in JavaScript to execute the code if condition is true or false.
There are three forms of if statement.
If Statement
If else statement
if else if statement
JavaScript If statement
if is most basic statement of Decision making statement. It tells to program to
execute a certain part of code only if particular condition or test is true.
Syntax
Syntax
if(expression)
{
//set of statements
}
Example
<script>
var a=10;
if(a>5)
17
{
document.write("value of a is greater than 5");
}
</script>
JavaScript if-else statement
In general it can be used to execute one block of statement among two blocks.
Syntax
if(expression)
{
//set of statements
}
else
{
//set of statements
}
Example of if..else statement
<script>
var a=40;
if(a%2==0)
18
{
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
Result
a is even number
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions.
Syntax
if(expression1)
{
//content to be evaluated if expression1 is true
}
else if(expression2)
{
//content to be evaluated if expression2 is true
}
else
{
//content to be evaluated if no expression is true
}
Example of if..else if statement
<script>
var a=40;
if(a==20)
{
document.write("a is equal to 20");
}
else if(a==5)
{
document.write("a is equal to 5");
}
else if(a==30)
19
{
document.write("a is equal to 30");
}
else
{
document.write("a is not equal to 20, 5 or 30");
}
</script>
Result
a is equal to 40
Looping Statement in
Set of instructions given to the compiler to execute set of statements until condition
becomes false is called loops. The basic purpose of loop is code repetition.
The way of the repetition will be forms a circle that's why repetition statements are
called loops. Some loops are available In JavaScript which are given below.
while loop
for loop
do-while
while loop
When we are working with while loop always pre-checking process will be occurred.
Pre-checking process means before evolution of statement block condition part will
be executed. While loop will be repeats in clock wise direction.
20
Syntax
while (condition)
{
code block to be executed
}
Example of while loop
<script>
var i=10;
while (i<=13)
{
document.write(i + "<br/>");
i++;
}
</script>
Result
10
11
12
13
21
do-while loop
In implementation when we need to repeat the statement block at least 1 then go for
do-while. In do-while loop post checking of the statement block condition part will be
executed.
syntax
do
{
code to be executed
increment/decrement
}
while (condition);
Example of do-while loop
Example
<script>
var i=11;
do{
22
document.write(i + "<br/>");
i++;
}while (i<=15);
</script>
Result
11
12
13
14
15
for Loop
For loop is a simplest loop first we initialized the value then check condition and then
increment and decrements occurred.
23
Steps of for loop
Syntax
for (initialization; condition; increment/decrement)
{
code block to be executed
}
Example of for loop
Example
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
Result
1
2
3
4
5
24
Switch Statement
The switch statement is used in JavaScript to execute one code from multiple
expressions.
Example
switch(expression)
{
case value1:
statement;
break;
case value2:
statement;
break;
......
default:
statement;
}
Note: default code to be executed if above values are not matched
25
Note: in switch statement all the cases will be evaluated if we do not use break
statement.
Example of switch statement in javascript.
Example
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
Result
Output: B Grade
Example of switch case in javascript
Example
<html>
<head>
<script>
function myFunction()
{
var day;
day=Number(document.getElementById("first").value);
switch (day)
{
case 1:
day = "Sunday";
26
break;
case 2:
day = "Monday";
break;
case 3:
day = "Tuesday";
break;
case 4:
day = "Wednesday";
break;
case 5:
day = "Thursday";
break;
case 6:
day = "Friday";
break;
case 7:
day = "Saturday";
break;
default:
day="Enter valid number"
}
document.getElementById("demo").innerHTML =day;
}
</script>
</head>
<body>
<p>Enter any number (1 to 7):</p>
<input id="first">
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
Result
Enter any number (1 to 7):
Try it
27
Function
An important part of JavaScript is the ability to create new functions within <script>
and </script> tag. Declare a function in JavaScript using function keyword. The
keyword function precedes the name of the function.
Syntax
function functionName(parameter or not)
{
.........
.........
}
Example of JavaScript using Function
Example
<html>
<head>
<script>
function getname()
{
name=prompt("Enter Your Name");
alert("Welcome Mr/Mrs " + name);
}
</script>
</head>
<form>
<input type="button" value="Click" onclick="getname()"/>
</form>
</html>
Array JavaScript
Array are used to represents the group of elements into a single unit or consecutive
memory location. Each and every element what we are entering into the array is
going to be stored in the array with the unique index starting from zero. Through the
28
indexes we can store the data or elements into the array or we can get the elements
from the array.
To declare an array in javascript we need new keyword. To create an array you use
new Array(n) where n was the number of slots in the array or new Array() omitting the
size of an array.
Note: Whenever we create any array in javaScript without specifying the size then it
well create array object with the zero size.
Syntax
myarray = new array(5);
Example of array in JavaScript
Example
<html>
<head>
<script type="text/javascript">
function arrayex()
{
myarray = new Array(5)
myarray[0] = 10
myarray[1] = 20
myarray[2] = 30
myarray[3] = 40
myarray[4] = 50
sum = 0;
for (i=0; i<myarray.length; i++)
{
sum = sum + myarray[i];
}
alert(sum)
}
</script>
</head>
<body>
<input type="button" onclick="arrayex()" value="click here">
</body>
</html>
29
Function used in Array
Here we will discuss about some functions which are frequently used in array
concept in JavaScript.
Function Discription
concat()
To concats the elements of one array at the end of another array and returns
an array.
sort()
To sort all elements of an array.
reverse()
To reverse elements of an array.
slice()
To extract specified number of elements starting from specified index without
deleting them from array.
splice()
It will extract specified number of elements starting from specified index and
deletes them from array.
push()
To push all elements in array at top.
pop()
To pop the top elements from array.
JavaScript Dialog box
All JavaScript dialog box is a predefined function which is used for to perform
different-different task. Some function are given below;
function
Discription
alert()
To give alert message to user.
prompt()
To input value from used.
confirm()
To get confirmation from user before executing some task.
Alert()
Alert function of java script is used to give an alert message to the user.
Alert function example
Example
30
<!doctype html>
<html>
<head>
<script>
function alertmsg()
{
alert("Alert function call");
}
</script>
</head>
<form>
<input type="button" value="Click Me" onclick="alertmsg()"/>
</form>
</html>
Result
prompt()
Prompt function of java script is used to get input from the user.
prompt() function example
Example
<!doctype html>
<html>
<head>
<script>
function alertmsg()
{
a=prompt("Enter your name:");
alert(a);
}
</script>
</head>
<form>
<input type="button" value="Click Me" onclick="alertmsg()"/>
</form>
</html>
31
confirm()
confirm function of java script is used to get confirmation from user before executing
some task.
confirm() function example
Example
<!doctype html>
<html>
<head>
<script>
function alertmsg()
{
a=prompt("Enter your name:");
confirm(a);
}
</script>
</head>
<form>
<input type="button" value="Click Me" onclick="alertmsg()"/>
</form>
</html>
Window Object
The window object represents a window in browser. An object of window is created
automatically by the browser.
Window is the object of browser, it is not the object of javascript. The javascript
objects are string, array, date etc. It is used to display the popup dialog box such as
alert dialog box, confirm dialog box, input dialog box etc.
32
The window methods are mainly for opening and closing new windows. The following
are the main window methods. They are:
Methods of window object
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.
Document Object
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.
33
Methods of document object
Method
Description
write("string")
writes the given string on the document.
writeln("string")
Same as write(), but adds a newline character after each statement.
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.
Event in JavaScript
All objects have properties and methods. In addition, some objects also have
"events". Events are things that happen, usually user actions, that are associated
with an object. The "event handler" is a command that is used to specify actions in
response to an event. Below are some of the most common events:
Event
Discription
onLoad
Occurs when a page loads in a browser
onUnload
occurs just before the user exits a page
onMouseOver
occurs when you point to an object
onMouseOut
occurs when you point away from an object
onSubmit
occurs when you submit a form
onClick
occurs when an object is clicked
34
Events and Objects
Events are things that happen, actions, that are associated with an object. Below are
some common events and the object they are associaated with:
Event
Object
onLoad
Body
onUnload
Body
onMouseOver
Link, Button
onMouseOut
Link, Button
onSubmit
Form
onClick
Button, Checkbox, Submit, Reset, Link
getElementById
The document.getElementById() method returns the element of specified id. In
below example we receive input from input field by using document.getElementById()
method, here document.getElementById() receive input value on the basis on input
field id. In below example "number" is the id of input field.
Example
<html>
<body>
<head>
<script type="text/javascript">
function squre()
{
var num=document.getElementById("number").value;
alert(num*num);
}
</script>
</head>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="squre" onclick="squre()"/>
</form>
</body>
</html>
35
Result
Enter No:
Code Explanation
var
num=document.getElementById("number").value; In
this
code
getElementById received value from input field which have id number.
Square of any number in javascript
Example
<html>
<body>
<head>
<script type="text/javascript">
function squre()
{
var num=document.getElementById("number").value;
var result=num*num;
document.getElementById("answer").value=result;
}
</script>
</head>
<form>
Enter No:<input type="text" id="number" name="number"/>
<input type="button" value="squre" onclick="squre()"/>
<input id="answer"/>
</form>
</body>
</html>
Result
Enter No:
JavaScript Forms Validation
Forms validation is important things other wise user input wrong data, so we need to
validate given data by user before submit it on server.
36
The JavaScript provides the facility to validate the form on the client side so
processing will be fast than server-side validation. So, most of the web developers
prefer client side form validation using JavaScript.
Here i will show you how to validate any input field like user name can not be blank.
In below example input are can not be blank.
Example
<html>
<head>
<script>
function form_validation(){
var name=document.myform.name.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}
}
</script>
</head>
<body>
<form name="myform" method="post" action="register.php" onsubmit="return
form_validation()" >
Name: <input type="text" name="name">
<input type="submit" value="submit">
</form>
</body>
</html>
Result
Name:
submit
Email validation
We can validate the email with the help of JavaScript. Here we check the condition
related to any email id, like email if must have "@" and "." sign and also email id must
be at least 10 character.
There are many criteria that need to be follow to validate the email id such as:
37
email id must contain the @ and . character
There must be at least one character before and after the @.
There must be at least two characters after . (dot).
Example
<html>
<head>
<script>
function email_validation()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n
dotposition:"+dotposition);
return false;
}
}
</script>
</script>
</head>
<body>
<form name="myform" method="post" action="#" onsubmit="return
email_validation();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form></body>
</html>
Result
Email:
register
JavaScript Password Validation
Here i will show you how to validate any password field like password field can not be
blank and length of password is minimum 8 character.
Example
38
<html>
<head>
<script>
function pass_validation()
{
var password=document.myform.password.value;
if (password==null || password=="")
{
alert("password can't be blank");
return false;
}
else if(password.length<8)
{
alert("Password must be at least 8 characters long.");
return false;
}
}
</script>
</head>
<body>
<form name="myform" method="post" action="register.php" onsubmit="return
pass_validation()" >
Password: <input type="password" name="password">
<input type="submit" value="submit">
</form>
</body>
</html>
Result
Password:
submit
Re-type Password Validation
Example
<html>
<head>
<script>
function pass_validation()
39
{
var firstpassword=document.f1.password1.value;
var secondpassword=document.f1.password2.value;
if(firstpassword==secondpassword){
return true;
}
else{
alert("password one and two must be same!");
return false;
}
}
</script>
</head>
<body>
<form name="f1" action="/JavaScript/Index" onsubmit="return pass_validation()">
Password:<input type="password" name="password1" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>
</body>
</html>
Result
Password:
Re-enter Password:
Submit
40