WT Unit 5
WT Unit 5
WT Unit 5
variables, scope of variables, functions. event handlers (onclick, onsubmit etc.), Document
Object Model, Form validation.
Prepared By
A.Kiran kumar
Assistant Professor
CMRTC
JavaScript
• JavaScript is a client-side, object-oriented scripting language that is used to handle
and validate client-side data before submitting it to the server.
• JavaScript is used to create client-side dynamic pages.
• It executes on the browser and therefore reduces the load on the server.
• JavaScript is a lightweight scripting language.
• Javascript is an interpreted language.
• JavaScript is Platform Independent language.
• Java script is a Dynamically typed language.
History:
• JavaScript, formerly known as LiveScript, has been developed by Netscape and Sun
Microsystems.
• JavaScript was developed by Brendan Eich in 1995, and appeared in Netscape, a
popular browser of that time.
Browsers use their own JavaScript Engines to execute the JavaScript code. Some
commonly used browsers are listed below:
•Chrome uses a V8 engine.
•Firefox uses the SpiderMonkey engine.
•Microsoft Edge uses the ChakraCore engine.
•Safari uses the SquirrelFish engine.
• Client-side Scripting:
•A client-side script is a program that is processed within the client browser.
• These kinds of scripts are small programs that are downloaded, compiled, and run by the
browser.
• JavaScript is an important client-side scripting language and is widely used in dynamic
websites.
JavaScript Features
Light Weight: JavaScript is a lightweight scripting language because it is made for data
handling at the browser level only.
Dynamic Typed: JavaScript supports dynamic typing which means types of the variable
are defined based on the stored value.
For example, if you declare a variable x then you can store either a string or a Number type
value. This is known as dynamic typing.
Object-Based Language: JavaScript is an object-based scripting language that provides
built-in objects like String, Math, Date, etc.
Functional Style: This implies that JavaScript uses a functional approach, even objects are
created from the constructor functions.
Platform Independent: This javascript is platform-independent means that you can simply
write the script once and run them on any platform or any browser
Prototype-based: JavaScript is a prototype-based scripting Language. This means
javascript uses prototypes instead of classes.
Interpreted: JavaScript is an interpreted language which means the script written inside
javascript is processed line by line and is not compiled before execution.
Advantages of JavaScript
1.JavaScript makes the webpage more interactive and dynamic.
2.JavaScript can save server traffic by validating the user inputs before sending data to
the server.
3.JavaScript can be used to store client-side cookies to store data on the client-side and
then read or delete them.
4.JavaScript is lightweight object-based Scripting language.
Disadvantages or Limitations:
• JavaScript is not capable to write multi-threading or multiprocessor code.
• JavaScript can't be used for developing networking applications.
• JavaScript can only be used on the client side i.e. for frontend development.
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
•Client-side validation,
•Dynamic drop-down menus,
•Displaying date and time,
•Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box
and prompt dialog box),
•Displaying clocks etc.
Frameworks of JS:
• Angular JS
• JQuery
• React
• Meteor
• Polymer etc
Syntax of JS:
JS code can be embedded in HTML using Script tag inside head tag
<html>
<head>
<script language="javascript" type="text/javascript">
//JS code
</script>
</head>
<body> </body>
</html >
Note:
Script tag has language and type attributes
The language attribute specifies that we are using JavaScript.
The text/javascript is the content type that provides information to the browser about the
data.
How to run Java Script
The browser is responsible for running JavaScript code
Ex:
Dis adv:
• If the code size increases, programmer may get confusion
Ex Internal JavaScript
Java Script Code and html code the in same document
<html>
<head>
<script type="text/javascript">
function msg()
{
document.write("Hello Javascript");
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html> output: Hello Javascript
Welcome to Javascript
2. External Javascript:
• HTML code will be written in html file.
• JavaScript code will be written in separate file with extension .js.
• We can include the javascript code Html with help of the src attribute othe f script tag.
Adv:
• Even though the code increases, the programmer can understand the code easily
• Reusability of one JS file in multiple Html files
Dis adv:
• No.of file will be increased
Ex to illustrate External JavaScript
Ex:hello.js
function msg()
{
document.write("Hello Javatscript");
}
Include the JavaScript file into Html page.
It calls the JavaScript function on button click.
index.html
<html>
<head>
<script type="text/javascript" src=“hello.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
output: Hello JavaScript
Welcome to JavaScript
JAVA SCRIPT DATA TYPES
Data type:The Data type specifies what type of data the variable can hold.
JavaScript is a dynamic type language, means you don't need to specify type of the variable
because it is dynamically used by JavaScript engine.
You need to use var here to specify the data type. It can hold any type of values such as
numbers, strings etc.
JavaScript has dynamic types. This means that the same variable can be used to hold
different data types:
For example:
var a=10;//holding number
var b="cherry";//holding string
There are two types of data types in JavaScript.
1.Primitive data type
1. Strings
A string is a sequence of characters
Strings are written with quotes. You can use single or double quotes:
Ex: var sname=“cherry”;
2. Numbers
JavaScript has only one type of numbers.
Numbers can be written with, or without decimals:
Ex : var x=10;
var x=10.5;
3.Booleans: Booleans are often used in conditional testing.
Booleans can only have two values: true or false.
var x = 5;
var y = 6;
2. object: An object is an entity that has a state and behavior. It should exist in the world.
• In real life, a car is an object.
• A car has properties like weight and color, and methods like start and stop:
<script>
emp={id:102,name:"cherry",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
3.RegExp:It represents regular expression.
Difference between
var vs let:
• var and let are both for variable declaration in JS but the difference i.e that
• var is function scoped
• let is block scoped
var:
{
var x=2;
}
// x can be accessed here
let:
{
let x=2;
}
//x cannot be accessed here
Java Script Operators
What is an Operator?
In JavaScript, an operator is a special symbol used to perform operations on operands
(values and variables).
Operands are the input values that we pass to the operator to perform operation.
For example, var sum=19+7;
Here + is an operator that performs addition, and 19 and 7 are operands.
There are following types of operators in JavaScript.
1.Arithmetic Operators
2.Assignment Operators
3.Comparison (Relational) Operators
1.Bitwise Operators
2.Logical Operators
3.Special Operators
1.Arithmetic Operators:
Arithmetic operators are used to perform arithmetic operations on the operands.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
Ex:
2.Assignment operators
Assignment operators are used to assign values to variables.
For Ex: var x = 5;
Here, the = operator is used to assign value 5 to variable x.
LHS=RHS
LHS should be variable
RHS may be a variable, value or expression
Operator Meaning
= Assigns to
+= add and assign to
-= subtract and assign to
*= multiply and assign to
/= divide and assigns to
%= modulus and assigns to
3.Relational Operators
Relational Operators are used to check relation between two variables.
Mainly used for the purpose of comparing.
Ex: a>b; Relational Operators returns “Boolean” value .i.e it will return true or false.
Operator Meaning
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
4. Logical Operators: are used when we want to check multiple conditions together.
Used to construct compound conditions.
The logical operators are
Operator Meaning
&& Logical AND (Both conditions must be true)
|| Logical OR (Atleast One Condition true)
! Logical Not (Given condition will be reversed )
5.JavaScript Bitwise Operators
The bitwise operators perform bitwise operations on operands
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<< Bitwise Left Shift
>> Bitwise Right Shift
6.String Operators
In JavaScript, you can also use the + operator to concatenate (join) two or more strings.
+ Combine two strings
num+num=addition
string+num=concatenation
num+string=concatenation
string+string=concatenation
Control statements
Control statements that can be used to control the flow of the program. Such statements
are called control statements.
Control statements are statements that are executed randomly and repeatedly.
They are useful to write better and more complex programs.
switch(expression)
{
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
default:
code to be executed if above values are not matched;
}
<script> Ex to illustrate switch case
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> output: B Grade
Loops:
• If you want to repeat a particular statement many times then use loops.
• The JavaScript loops are used using for, while, do while or
for-in loops. It makes the code compact. It is mostly used in array.
There are four types of loops in JavaScript.
1.for loop
2.while loop
3.do-while loop
4.for-in loop
1.while:
• It is used to execute the code repeatedly, while the condition is TRUE
• It checks the condition and execute the code; again it repeats the same process as
long as the condition is TRUE, once the condition is false, it stops the loop.
• It is also called entry called loop.
Syntax:
while(condition)
{
statements
}
Ex to illustrate while loop
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
Output:
11
12
13
14
15
11
12
13
14
15
2.dowhile
• It is also same as while loop, to execute the code repeatedly as long as the condition is TRUE
• But, code is once whether condition is true or false. It is also called exit loop
syntax
do{
code to be executed
}while (condition);
Ex: to illustrate dowhile
<script>
var i=21;
do{ output:
document.write(i + "<br/>"); 21
i++; 22
}while (i<=25); 23
</script> 24
25
3.forloop:
• It is used to execute the code repeatedly, while the condition is TRUE
• It is also same as while, but we will write the loop related statements (initialization,
condition and inc/dec) in a single line so that it will be easy to understand.
Syntax:
for(initialization; condition; increment/decrement)
{
statements
}
Ex: to illustrate for loop
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
JavaScript Functions
Function: Function is a block of code to perform a specific task or operations.
JavaScript function can be call many times to reuse the code.
In Javascript we 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.
The body of function is written within {}.
Syntax
function functionName([arg1, arg2, ...argN])
{
//code to be executed
}
Calling a Function: we can call a function directly with functionname
functionname();
Advantage of JavaScript function
1.Code reusability: We can call a function several times so it save coding.
2.Less coding: It makes our program compact. We don’t need to write many lines of code
each time to perform a common task.
•Function makes the program easier as each small task is divided into a function.
•Function increases readability.
Example of function in JavaScript that does not has Parameters.
<html>
<head>
</head>
<body>
<script>
function msg()
{
document.write("javascript is popular scripting language");
}
msg();
</script>
</body>
</html> output: javascript is popular scripting language
JavaScript Function Parameters
A function can also be declared with parameters. A parameter is a value that is passed when
declaring a function. We can call function by passing arguments.
Example of function that has one parameter.
<html>
<head>
<script>
function sum(x,y)
{
document.write(x+y);
}
</script>
</head>
<body>
<input type="button" value="click" onclick="sum(5,5)"/>
</body>
</html> output:10
Java Script Function with Return Value
We can call a 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.
Example of function that returns value
funret.html
<html>
<head> </head>
<body>
<script>
function add(x,y)
{
return(x+y);
}
</script>
<script>
document.write(add(10,5));
</script>
</body> </html> output:15
Java Script objects
object
String
Array
Number
Date
Boolean
Window
JavaScript Objects
1.Object:
A JavaScript object is an entity having state and behavior (properties and method).
For example : Student,car, pen, bike, etc.
• JavaScript is an object-based language. Everything is an object in JavaScript.
• JavaScript is template based not class based. Here, we don't create class to get the
object. But, we direct create objects.
Creating Objects in JavaScript
There are 3 ways to create objects.
1.By object literal
2.By creating instance of Object directly (using new keyword)
3.By using an object constructor (using new keyword)
1) JavaScript Object by object literal
The syntax of creating an object using object literal is given below:
object={property1:value1,property2:value2.....propertyN:valueN}
property and value is separated by : (colon).
<script>
document.getElementById('txt').innerHTML=today;
</script>
Output:
Current Date and Time: Sun Apr 16 2017 12:37:28 GMT+0530 (India Standard Time)
5.JavaScript Boolean
• JavaScript Boolean is an object that represents value in two states: true or false. You
can create the JavaScript Boolean object by Boolean() constructor as given below.
Boolean b=new Boolean(value);
JavaScript Boolean Example
<script>
document.write(10<20);//true
document.write(10<5);//false
</script>
6.JavaScript Number Object
• The JavaScript number object . It may be an
integer or floating-point.
• By the help of the Number() constructor, you can create a number object in JavaScript.
For example:
1.var n=new Number(value);
If the value can't be converted to a number, it returns NaN(Not a Number) that can be
checked by isNaN() method.
You can direct assign a number to a variable also.
For example:
var x=102;//integer value
var y=102.7;//floating point value
var z=13e4;//exponent value, output: 130000
var n=new Number(16);//integer value by number object
Output: 102 102.7 130000 16
7.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.
Methods of window object
The important methods of window object are as follows:
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.
Example of alert() in javascript
It displays alert dialog box. It has message and ok button.
alertbox.html
<script type="text/javascript">
function msg(){
alert("Hello Alert Box");
}
</script>
<input type="button" value="click" onclick="msg()"/>
Example of confirm() in javascript
It displays the confirm dialog box. It has message with ok and cancel buttons.
Confirm.html
<script type="text/javascript">
function msg(){
var v= confirm("Are u sure?");
if(v==true){
alert("ok");
}
else{
alert("cancel");
}
}
</script>
<input type="button" value="delete record" onclick="msg()"/>
Example of prompt() in javascript
It displays prompt dialog box for input. It has message and text field.
Prompt.html
<script type="text/javascript">
function msg(){
var v= prompt("Who are you?");
alert("I am "+v);
}
</script>
<input type="button" value="click"
onclick="msg()"/>
Java Script Events(Event Handlers)
Onfocus
Onmouseout
onblur
Some of the HTML Events And Event Handlers
Mouse events:
Event Performed Event Handler Description
In the following javascript Ex we are calling a function myfun() as soon as a button is clicked
click.html
<html>
<head>
<script type="text/javascript">
function myfun()
Syntax
< onsubmit=" ">
Ex to iilustrate onsubmit() event:
onsubmit.html
<html>
<head>
<script type="text/javascript">
function myfun()
{
Alert("you have entered" +form1.text1.value);
}
</script>
</head>
<body>
<form name="form" onsubmit=myfun();>
3.onmouseover(): When the cursor of the mouse comes over the element
Onmouse.html
<html>
<head>
</head>
<body>
<script language="Javascript" type="text/Javascript">
function mouseoverevent()
{
alert("This is Mouseover Event");
}
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
4.onload:This event occurs when an object has been loaded.
It is most often used with in the body element to execute a script once a web page has
completely loaded.
Ex: onload.html
<html><head>
<script type=”text/javascript”>
function page_load()
{
alert(“ page loaded successfuly”);
}
</script></head>
<body onload=”page_load()”>
<p> to load the page refresh or reopen</p>
</body> </html>
Document Object Model, Form validation.
Document Object Model
Document Object Model(DOM)
• 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.
• The DOM defines a standard for accessing Html and xml documents.
• The 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.
• In the DOM, all HTML elements are defined as objects.
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:
Method Description
innerex.html
<html>
<body>
<p id="demo">Inner html</p>
<script>
document.getElementById("demo").innerHTML = "Hello Javascript!";
</script>
</body> output: Hello Javascript
</html>
JS Form Validation:
• It is important to validate the form submitted by the user because it can have
inappropriate values. So, validation is a must to authenticate user.
• 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.
• Through JavaScript, we can validate name, passwords, email, date, mobile numbers
and more fields.
• Java script is used to validate forms, that means checking the proper information are
entered to the users in the form fields before submission.
Java script is used to validate following
• To check user entered text has the current no of characters
• To check user Enter emaild id valid or not
• To validate user entered fields length valid or not
• To check user entered valid date and format.
• If the selected item from drop down valid or not
JavaScript form validation example
• 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.
validation.html
<html>
<head>
<script>
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="abc.jsp" onsubmit="return validateform()"
>
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
JavaScript email validation
We can validate the email with the help of JavaScript.
There are many criteria that need to be follow to validate the email id such as:
•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).
email.html Ex to illustrate email validation by using javascript
<html >
<head>
<script>
function validateEmail(emailId)
{
var mailformat = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(emailId.value.match(mailformat))
{
document.form1.text1.focus();
return true;
}
else
{
alert("Invalid email address.");
document.form1.text1.focus();
return false;
} }
</script>
</head>
<body>
<div>
<h2>JavaScript email validation</h2>
<form name="form1" action="#">
Email: <input type='text' name='email'/></br></br>
<input type="submit" name="submit" value="Submit"
onclick="validateEmail(document.form1.email)"/>
</form>
</div>
</body>
</html>