You are on page 1of 92

CONTENTS • Java script: Introduction

• Data types, Operators


• Statements
• Loops
• Functions
• Events
• Error and Exception Handling
• DOM
• Form Validation
• Objects
• Regular Expression
JAVA SCRIPT Introduction
• JavaScript is not Java, or even related to Java
• The original name for JavaScript was “LiveScript”
• The name was changed when Java became popular
• Now that Microsoft no longer likes Java, its name for their JavaScript dialect is “Active Script”

• Statements in JavaScript resemble statements in Java, because both languages borrowed


heavily from the C language

• JavaScript should be fairly easy for Java programmers to learn


• However, JavaScript is a complete, full-featured, complex language
• JavaScript are used to add functionality to HTML pages

JavaScript is reasonably platform-independent


• 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.

What can JavaScript Do?


• JavaScript can dynamically modify an HTML page

• JavaScript can react to user input

• JavaScript can validate user input

• JavaScript is a full-featured programming language

• JavaScript user interaction does not require any communication with the server
Where it is used?
It is used to create interactive websites. It is mainly used for:
• Client-side validation
• Dynamic drop-down menus
• Displaying date 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.
Features of JavaScript
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)

To Put a JavaScript Into an HTML Page:


<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
(i) Inline JavaScript

• When java script is written within the html element using attributes related to events
of the element then it is called as inline java script.

Example: <html> <form> <input type="button"


value="Click" onclick="alert('Button Clicked')"/>
</form> </html>

Output:
(ii) Internal JavaScript
• When java script is written within the section using element then it is called as internal java script.

<html>
<head>
<script>
function msg()
Example: { alert("Welcome in JavaScript"); }
</script>
</head>
<form>
<input type="button" value="Click" onclick="msg()"/>
</form>
</html>

Output:
click
(iii) External JavaScript
• Writing javascript in a separate file with extension .js is called as external java script.
• For adding the reference of an external java script file to html page, use tag with src attribute.
Example: <script type="text/javascript" src="filename.js"/>
• Create a file with name message.js and write the following java script functions in it.
function msg() { alert("Welcome in JavaScript"); }

<html> <head>
<script type="text/javascript" src="message.js">

Example: </script>
</head>
<body>
<form>
output:
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Simple User Interaction: alert(), confirm(), and prompt()

There are three built-in methods of doing simple user interaction


– alert(msg) alerts the user that something has happened.
• Display a message in a dialog box.

– confirm(msg) Display a message in a dialog box with two buttons: "OK" or "Cancel".

• returns true if the user click "OK". Otherwise it returns false.

- prompt(msg, default) Display a message and allow the user to enter a value.
• The second argument is the "default value" to be displayed in the input textfield.
• Without the default value, "undefined" is shown in the input textfield.
• If the user click the "OK" button, prompt() returns the value in the input textfield as a string.
• If the user click the "Cancel" button, prompt() returns null.
alert(), confirm(), and prompt()
JAVASCRIPT COMMENTS
There are two types of comments in JavaScript:
1) Single-line Comment: It is represented by double forward slashes (//).
It can be used before and after the statement.

<script>
Ex: // It is single line comment
document.write("hello javascript");
</script>

2) Multi-line Comment: It can be used to add single as well as multi line comments. It is
represented : /* your code here */

<script>
Ex: /* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>
IDENTIFIER
JavaScript Identifiers are names given to variables, functions, etc.

It is the same as identifiers in other programming languages like C, C++, Java, etc.
except that it allows an additional character – '$'.

• Contains only 'A' – 'Z', 'a' – 'z', '0' – '9', '_', '$'
• First character cannot be a digit
• Case-sensitive
• Cannot be reserved words or keywords
VARIABLE
It is simply a name of storage location. There are two types of variables in JavaScript :
-local variable and global variable.
Rules while declaring a variable (also known as identifiers):

• 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.

<script>
Example: var x = 10; Output:
var y = 20;
30
var z=x+y;
document.write(z);
</script>

• Dynamic binding – a variable can hold any type of value


• If a variable is used without being declared, the variable is created automatically.
(1) local variable
Declared inside block or function using “var” keyword. It is accessible within the function or block only.
<script> <script>
function abc(){ If(10<13){
var x=10; //local variable Or, var y=20; // local variable
Example: } }
</script> </script>

(2) global variable


Declared outside the function or declared with window object. It is accessible from any function.

<script>
var data=200; //gloabal variable
function a(){
document.writeln(data);
}
function b(){
Example: document.writeln(data);
}
a(); //calling JavaScript function
b();
</script>
DATA TYPES
• Primitive data types
– Number: integer & floating-point numbers
– Boolean: true or false
– String: a sequence of alphanumeric characters
– Null: to represent nothing.
– Undefined: to represent the value of an unintialized variable

• non-primitive data type


– Object: represents instance through
which we can access members
– Array: a sequence of similar values
– RegExp: represents regular expression
OPERATORS
Symbols that are used to perform operations on operands.
Arithmetic Operators +, -, *, /, %, ++, --

Comparison operators(Relational) Operators ==, !=, >, >=, <, <=,


Types of operators: ===, !== (Strictly equals and strictly not equals)
i.e., Type and value of operand must match / must not
match

Logical Operators ! – Logical NOT, && – Logical AND, || – Logical OR

Assignment operators =, +=, -=, *=, /=, %=

Bitwise operators &, |, ^, ~, >>, <<, >>>

String concatenation operator +

Special Operators (?:), ,(Comma Operator allows multiple


expressions to be evaluated as single statement),
instanceof, new, typeof,
(1) typeof operator
It is an unary operator that tells the type of its operand.
Returns a string which can be "number", "string", "boolean", "object", "function", "undefined", and "null"

var x = "hello", y;
alert("Variable x value is " + typeof x );
alert("Variable y value is " + typeof y );
alert("Variable x value is " + typeof z );
(2) == vs ===
// Type conversion is performed before comparison
var v1 = ("5" == 5); // true

// No implicit type conversion. True if only if both types & values are equal
var v2 = ("5" === 5); // false

var v3 = (5 === 5.0); // true

var v4 = (true == 1); // true (true is converted to 1)

var v5 = (true == 2); // false (true is converted to 1)

var v6 = (true == "1") // true


CONDITIONAL STATEMENTS
In JavaScript we have the following conditional statements:
• if statement - to execute some code only if a specified condition is true

• if...else statement - to execute some code if the condition is true and another code if the condition is false

• if...else if....else statement - to select one of many blocks of code to be executed

• switch statement - to select one of many blocks of code to be executed


Conditional Statements(1)
if (condition) {
(1) Example of if statement: code to be executed if condition is true }

<script> Output: value of a is greater than 10


var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>

<script>
(2) Example of if …else statement: var a=20;
if(a%2==0){
if (condition)
{ document.write("a is even number");
code to be executed if condition is true }
}
else else{
{
code to be executed if condition is not true document.write("a is odd number");
} }
</script>

Output: a is even number


Conditional Statements(2)

(3) Example of if…else…if statement:


<script>
var a=20;
if(expression1){ if(a==10){
//content to be evaluated if expression1 is true document.write("a is equal to 10");
}
}
else if(expression2){
//content to be evaluated if expression2 is true else if(a==15){
} document.write("a is equal to 15");
else if(expression3){ }
//content to be evaluated if expression3 is true else if(a==20){
} document.write("a is equal to 20");
else{
}
//content to be evaluated if no expression is true
} else{
document.write("a is not equal to 10, 15 or 20");
}
</script>

Output: a is equal to 20
Conditional Statements(3) <script>
var grade='B';
(4) Example of switch statement: var result;
switch(grade){
switch(expression){ case 'A':
case value1:
code to be executed; result="A Grade";
break; break;
case value2: case 'B':
code to be executed;
break; result="B Grade";
...... break;
case 'C':
default:
code to be executed if above values are not matched; result="C Grade";
} break;
default:
result="No Grade"; Output: B Grade
}

document.write(result);
</script>
LOOPS
Loops are used to iterate the piece of code using for, while, do while or for-in loops.
It makes the code compact.

There are four types of loops in JavaScript.

1. for loop
2. while loop
3. do-while loop
4. for-in loop
FUNCTIONS
Used to perform operations.
We can call function many times to reuse the code.

Advantage:

There are mainly two advantages of functions:

• Code reusability: We can call a function several times so it save coding.


• Less coding: It makes our program compact. We don’t need to write many lines of
code each time to perform a common task.

Syntax: function functionName([arg1, arg2, ...argN]){


//code to be executed
}

Functions can have 0 or more arguments.


Functions(1)
function functionName([arg1, arg2, ...argN]){
Syntax: //code to be executed
Example of call function by passing arguments:
}
Functions can have 0 or more arguments.
<script>
Example of function without arguments: function getcube(number){
<script> alert(number*number*number);
}
function msg(){
</script>
alert("hello! this is message"); <form>
} <input type="button" value="click" onclick="getcube(4)"/>
</script> </form>
<input type="button" onclick="msg()"
value="call function"/>
<script>
function getInfo(a,b){
return a*b ; }
Ex. of function with Return Value: </script>
<script>
var x=getInfo(4,5);
document.write(x);
</script>
BUILT-IN FUNCTIONS
(I) isNaN(x): Determines whether a value is “Not a Number”
<html> <title>My first Javascript code</title> </head> OP :
EX.: <script>
document.write(isNaN(0));
document.write("</br>");
document.write(isNaN(-1.891));
document.write("</br>");
document.write(isNaN("12"));
document.write("</br>");
document.write(isNaN("2015/4/8"));
document.write("</br>");
document.write(isNaN("KIET"));
</script></body> </html>

(II) eval(expr) : evaluates an expression or statement


eval("3 + 4"); // Returns 7 (Number)
eval("alert('Hello')"); // Calls the function alert('Hello')
Built-in Functions(1)
(III) is Finite(x) : Determines if a number is finite
<html> <title>Javascript code</title>
</head>
Ex.: <script>
document.write(isFinite("12345"));
document.write("</br>");
document.write(isFinite("ABCD"));
document.write("</br>");
document.write(isFinite("123_456"));
</script> </html>

(IV) parseInt: Takes string as a parameter and converts to integer


<html> <title>Javascript code</title> </head>
<script>
document.write(parseInt("95"));
document.write("</br>");
document.write(parseInt("180 rooms"));
document.write("</br>");
document.write(parseInt("Todays count is 88"));
</script> </html>
EVENTS
• An event is an unexpected external occurrence. It is the change in the state of an object
• JavaScript-applications perform actions as a response to events.
• An event is a signal from the browser that something has happened.
• This process of reacting over the events is called Event Handling.
• Thus, js handles the HTML events via Event Handlers.

An event occurs as a result of some activity,

➢ A user clicks on a link in a page


e.g.: ➢ Page finished loaded
➢ Mouse cursor enter an area
➢ A preset amount of time elapses
➢ A form is being submitted

Javascript provides events and event handlers to handle user interactions.


EVENTS- Event Handlers(1)
• Event Handler – a segment of codes (usually a function) executed when an event occurs
• We can specify event handlers as attributes in the HTML tags.
• The attribute names typically take the form "onXXX" where XXX is the event name.
• e.g.: <a href="…" onClick="alert('Bye')">Other Website</a>
Events and their event handlers are listed :

(1) Mouse events: Event Performed Event Handler Description

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.


EVENTS- Event Handlers(2)

(2) Keyboard events: Event Performed Event Handler Description

Keydown & Keyup onkeydown & onkeyup When the user press and then release the key

Event Event Description


(3) Form events: Performed Handler

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form element

change onchange When the user modifies or changes the value of a form element
EVENTS- Event Handlers(3)
(4) Window/Document events:

Event Performed Event Handler Description

load onload When the browser finishes the loading of the page

unload onunload When the visitor leaves the current webpage, the browser unloads it

resize onresize When the visitor resizes the window of the browser

<html>
EVENTS PROGRAMS: <body onLoad="alert('Welcome to this page’)”>
//onUnload="alert('Thanks for visiting this page’)”//
(a) Load event:
<script>
document.write("The page is loaded successfully");
</script>
</body> </html>
EVENTS- Event Handlers(4)

(b) Click Event: <html> <h1> Javascript Events </h1><br><br>


<body>
<script language="Javascript" type="text/Javascript">
function clickevent() {
document.write("Welcome to WEB TECH!!!!!!!!!"); }
</script>
<form>
<input type="button" onclick="clickevent()" value="Click the Subject"/>
</form> </body> </html>

<html><body><h1> JS EVENTS</h1><br><br>
(c) MouseOver Event: <script>
function mouseoverevent() {
alert("WT is hub of technologies!!!!");
}
</script>
<b><p onmouseover="mouseoverevent()"> Keep cursor over me</p> </b>
</body> </html>
EVENTS- Event Handlers(5)
<html> <body>
(d) Focus Event : <h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
function focusevent() {
document.getElementById("input1").style.background=" yellow";
}
</script></body> </html>

<html>
<body>
(e) Keydown Event: <h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
function keydownevent() {
document.getElementById("input1");
alert("Pressed a key");
}
</script> </body> </html>
EVENTS- Event Handlers(5)
(f)Submit Event: <html>
<script>
function validate() {
alert("Textbox must not be left blank!!!");
}
</script>
<body>
<form onSubmit="validate()">
Enter name: <input type="text">
<input type="submit">
</form></body></html>

• If onSubmit event handler returns false, data is not submitted.


• If onReset event handler returns false, form is not reset
Error and Exception Handling
➢ An exception is the anomalous code that breaks the normal flow of the code. Such exceptions
require specialized programming constructs for its execution.
➢ exception handling is a process or method used for handling the abnormal statements in the
code and executing them.
Types of Errors
There can be three types of errors in the code:
i. Syntax Error: When a user makes a mistake in the pre-defined syntax of a programming language
ii. Runtime Error: An error that occurs during the execution of the program.
The codes which create runtime errors are known as Exceptions. Thus, exception handlers are
used for handling runtime errors.
iii. Logical Error: An error that may not produce the desired output, and may terminate abnormally.
Error Object:
When a runtime error occurs, it creates and throws an Error object.
An error object has two properties:
• name: sets or returns an error name.
• message: returns an error message in the string form.
Exception Handling Statements
There are following statements that handle if any exception occurs:
throw statements
try…catch statements
try…catch…finally statements. (2) catch{} statement:
(1) try{} statement: • It handles the error of the code .
• Contains either the user-defined exception handler or the
• Here, code which needs possible error testing
built-in handler.
is kept
• Executes when any error needs to be handled in the try block.
• If any error occur, it passes to the catch{} block
• Otherwise, the catch block is skipped.
for taking suitable actions and handle the error.
• Otherwise, it executes the code written within.

catch {} statement executes only after the execution of the try {} statement.
Also, one try block can contain one or more catch blocks.

(3) Throw Statement:

• User can define and throw their own custom errors(UDE)


• When throw statement is executed, the statements present after it will not execute.
• The control will directly pass to the catch block.
try…catch example :

<html> <body>
<script>
try{
Ex. var a= ["34","32","5","31","24","44","67"]; //a is an array
document.write(a); // displays elements of a
document.write(b);
//b is undefined but still trying to fetch its value. Thus catch block will be invoked
}catch(e){
alert("There is error which shows "+e.message); //Handling error
}
</script> </body> </html>

OP:
Throw example :
<html> <body>
<script>
try{
var num = prompt("Enter a number (1-2):", "1");
if (num == "1")
Ex.
throw "Error,Not allowed!!!";
else
if (num == "2")
throw 654987;
else
throw new Error ("Wrong Input!!!");
} catch( err ) {
alert(typeof(err) + "\n" + err);
} </script></body></html>

OP:
try … catch … finally example

<html><body> <script>
try{
document.write("Try block begins<br>");
eval ("10 + * 5"); // create a syntax error
} catch( errVar ) {
Ex. document.write("Exception caught<br>");
// errVar is an Error object, All Error objects have a name and message properties
document.write("Error name: " + errVar.name + "<br>");
document.write("Error message: " + errVar.message +"<br>");
} finally {
document.write("Finally block reached!<br>");
document.write("BYE");
}
</script> </body> </html>

OP:
Handling Exceptions
• The onError event handler is used.
• A method associated with the window object.
• It is called whenever an exception occurs
<html><head>
<title>onerror event handler example</title>
<script>
function errorHandler() OP:
Ex. {
alert("Error Ourred!");
}
// JavaScript is casesensitive, Don't write onerror!

window.onError = errorHandler();
</script> </head>
<body>
<script>
document.write("Hello there;
</script>
</body>
</html>
DOCUMENT OBJECT MODEL (DOM)

• The document object represents the whole html document.


• When a web page(html document) is loaded in the browser, it becomes a document object.
• Represent the current web page as a tree of Javascript objects
• It has properties and methods.
• Allows us to view/add/modify/delete page elements and attributes in script code after page has loaded.
• It is Browser-Independent language and platform independent.
• JavaScript can react to and also create new HTML events in the page
• Allows progressive enhancement.

• It is the object of window. So, window.document is same as => document


DOM(1)

DOM model is created as a tree of objects like this:


DOM(2) : Properties of document object
• Window Object: always at top of the hierarchy.
• Document object: HTML document becomes a document object when loaded into a window.
• Form Object: It is represented by form tags.
• Link Objects: It is represented by link tags.
• Anchor Objects: It is represented by a href tags.
• Form Control Elements: Form can have text fields, buttons, radio buttons, and checkboxes, etc.

Methods of Document Object:


Write(ln)(“string”): writes the given string on the document(ln: newline charcter at 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.
DOM(3) : Properties of document object
HTML DOM
html
<Table>
<ROWS>
<TR>
<TD>Car</TD>
Example: <TD>Scooter</TD>
</TR>
<TR>
<TD>MotorBike</TD>
<TD>Bus</TD>
</TR>
</ROWS>
</Table>
DOM(4)
What is the DOM?
• The DOM is a W3C (World Wide Web Consortium) standard.
• The DOM defines a standard for accessing documents:
• "The W3C 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."

The W3C DOM standard is separated into 3 different parts:

1. Core DOM - standard model for all document types


2. XML DOM - standard model for XML documents
3. HTML DOM - standard model for HTML documents

The HTML DOM is a standard object model and programming interface for HTML. It defines:

➢ The HTML elements as objects


➢ The properties of all HTML elements
➢ The methods to access all HTML elements
➢ The events for all HTML elements

In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
DOM(5)

HTML DOM Methods


• HTML DOM methods are actions we can perform (on HTML Elements).
• HTML DOM properties are values (of HTML Elements) that we can set or change.

The DOM Programming Interface

The HTML DOM can be accessed with JavaScript (and with other programming languages).
In the DOM, all HTML elements are defined as objects.
The programming interface is the properties and methods of each object.
• Property: a value that can be get or set.
• Method: an action performed (like add or deleting an HTML element).
Accessing field value by document object
(1) document.form1.name.value
To get the value of input text by user by using document.form1.name.value :
• 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.
<script>
function printvalue(){
var name=document.form1.name.value;
Example: alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>

OP:
(2) document.getElementById() method
It is to get value of the input text. But we need to define id for the input field.

<script>
function getcube(){
var number=document.getElementById("number").value;
Example: alert(number*number*number);
}
</script>

<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>

OP:
(3) document.getElementsByName() method

It returns all the element of specified name.

<script>
Ex. : To get all the genders: 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>

OP:
(4) document.getElementsByTagName() method
It returns all the element of specified tag name.

<script>>
function counth2(){
var totalh2=document.getElementsByTagName("h2"); OP:
Ex.: To count total number of h2 & h3 tags 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>
(5) innerHTML property

Useful for getting or replacing the content of HTML elements

<html> <body>
<script>
Ex.: To change the text inside P tag: function changeText(){
document.getElementById('wel').innerHTML = 'WELCOME TO JS!!!';
}
</script>
<p id ='wel'>Join Hands for Technologies</p>
<input type='button' onclick='changeText()' value='Change Text'/>
</body> </html>

OP:
(6) innerText Property
• Used to write the dynamic text on the html document which will be as a normal text.
• Used mostly to generate dynamic content such as writing validation message, password strength etc.

<html><body> <script>
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
Ex.: Password strength will be determined: msg="Strong Password"; }
else{
msg="Weak Password"; }
document.getElementById('mylocation').innerText=msg;
}
</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">No Input</span>
</form> </body>
</html>
OP:
FORM VALIDATION
It is very important to validate the form submitted by user because it may have some inappropriate values.

• Form validation normally used to occur at the server, after the client had entered all the necessary data and
then pressed the Submit button.
• If the data entered by a client was incorrect or was simply missing, the server would have to send all the data
back to the client and request that the form be resubmitted with correct information.

This was really a lengthy process which used to put a lot of burden on the server.

• JS allows us to validate the form on the client-side in order to make the data processing faster than
server-side validation.
• Validation can be applied for name, password, email, date, mobile numbers and more fields.

Functions of Form validation(2 Types):


(a) Basic Validation − Form checked to make sure all the mandatory fields are filled in.
(b) Data Format Validation − Data entered must be checked for correct form and value
FORM VALIDATION(1)

To understand the process of Basic Validation


OP:

Example:
Program
Next
Slide
Creating form to fill data
Calling validate() to validate data when onsubmit event is occurring
<html> <head> <title>Form Validation</title>
<script > <script>
// Form validation code will come here. function validate() {
</script> </head> if( document.myForm.Name.value == "" ) {
<body>
<form action = " " name = "myForm" onsubmit = "return(validate());"> alert( "Please provide your name!" );
<table cellspacing = "2" cellpadding = "2" border = "1"> document.myForm.Name.focus() ;
<tr> return false; }
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td> if( document.myForm.EMail.value == "" ) {
</tr> alert( "Please provide your Email!" );
<tr> document.myForm.EMail.focus() ;
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td> return false; }
</tr> if( document.myForm.Zip.value == "" || isNaN(
<tr> document.myForm.Zip.value ) ||
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td> document.myForm.Zip.value.length != 5 ) {
</tr>
<tr> alert( "Please provide a zip in the format #####." );
<td align = "right">Country</td>
<td> document.myForm.Zip.focus() ;
<select name = "Country"> return false; }
<option value = "-1" selected>[choose yours]</option> if( document.myForm.Country.value == "-1" ) {
<option value = "1">USA</option>
<option value = "2">UK</option> alert( "Please provide your country!" );
<option value = "3">INDIA</option> return false;
</select> }
</td></tr>
<tr> return( true );
<td align = "right"></td> }
<td><input type = "submit" value = "Submit" /></td> </script>
</tr> </table></form></body> </html>
FORM VALIDATION(2)

To understand the process of Format Validation

Example: To validate an entered email address.

✓ An email address must contain at least a ‘@’ sign and a dot (.).
✓ Also, the ‘@’ must not be the first character of the email address, and the last dot
must at least be one character after the ‘@’ sign.

Program Next Slide->>


e-mail Validation
<html> <body> <script>
function validateemail()
{
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>
<body>
<form name="myform" method="post" action=“ " onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form> </body> </html>
FORM VALIDATION(3)

<html><head>
Example: <script>
To validate function validate(){
var num=document.myform.num.value;
for if (isNaN(num))
{
numeric document.getElementById("numloc").innerHTML="Enter Numeric value only";
return false;
values }else{
return true;
}
}
</script></head>

<body>
<form name="myform" action=“ " onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>
</body></html>
JS OBJECTS
• It is an entity having state and behavior (properties and method). For example: book, pen etc.
• JavaScript is an object-based language. Everything is an object in JavaScript.
• Here, we don't create class to get the object. But, we direct create objects.
In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:

ObjectProperties
1. car.name = Fiat 2. car.model = 500 3. car.weight = 850kg 4.car.color = white

Methods
1.car.start() 2.car.drive() 3.car.brake() 4.car.stop()

• All cars have the same properties, but the property values differ from car to car.
• All cars have the same methods, but the methods are performed at different times.
Creating Objects in JavaScript
There are 3 ways to create objects.
(i) By object literal
Syntax: object={property1:value1,property2:value2.....propertyN:valueN}

Ex. <script>
emp={ id:101,name:“Abhineet Maitrey",salary:90000 }
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

(ii) By creating instance of Object directly (using new keyword)


Syntax: var objectname=new Object();
<script>
var emp=new Object();
emp.id=101;
Ex. emp.name=“Aviral Maitrey";
emp.salary=80000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Creating Objects……….
(iii) By using an Object constructor

• Here, it is required to create function with arguments.


• Each argument value can be assigned in the current object by using this keyword.
• The this keyword refers to the current object.

<script>
Ex. function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(102,“Shruti Pathak",60000);

document.write(e.id+" "+e.name+" "+e.salary);


</script>
OBJECTS(1)
Objects are variables too. But objects can contain many values.

• This code assigns many values (Fiat, 500, white) to a variable named car:
• The values are written as name:value pairs (name and value separated by a colon).

Object Properties
• The name:values pairs (in JS objects) are called properties.
Ex.: var person = {firstName:“Abhi", lastName:“Maitrey", age:15, eyeColor:"blue"};

Object Methods:
• Methods are actions that can be performed on objects.
• Methods are stored in properties as function definitions.
OBJECTS(2)
Accessing Object Properties:
• We can access object properties in two ways: objectName.propertyName. Ex. person.lastName;
Or
objectName["propertyName"] . Ex. person["lastName"];

<html>
<body>
<h2>Creating & accessing a JavaScript Object.</h2>

Example: Type:<p id="demo"></p>


Model: <p id="demo1"></p>
OP:
Color: <p id="demo2"></p>

<script>
var car = {type:"Fiat", model:"500", color:“White"};
document.getElementById("demo").innerHTML = car.type;
document.getElementById("demo1").innerHTML = car[“model”];
document.getElementById("demo2").innerHTML = car.color;
</script>
</body>
</html>
OBJECTS(3)
Accessing Object Methods

Syntax: objectName.methodName() Example: name= person.fullname();

<html><body>
<p>Creating and using an object method.</p>
We can access an object method with the code➔ <p>An object method is a function definition, stored as a property value.</p>
<p id="demo"></p>
<script>
var person = {
firstName: "Abhi",
lastName : "Maitrey",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName+" "+this.id; }
};
document.getElementById("demo").innerHTML = person.fullName();
</script></body></html>

OP:
THE DOCUMENT OBJECT

• A document is a web page that is being either displayed or created.


• It has a number of properties,used to manipulate the content of the page.

a) write or writeln
Html pages can be created by using the write or writeln methods of the document object.
Syntax: document.write (“String”); document.writeln (“String”);

Here, document is object name and write () or writeln () are methods. Symbol period is used as connector between object name and
method name. The difference between these two methods is new line character automatically added into the document.

Example: document.write(“<body>”); document.writeln(“<h1> Hello </h1>”);


ARRAY OBJECT
It is an object that represents a collection of similar type of elements.
Ex.
There are 3 ways to construct array: <script>
1. By array literal var emp=[“Abhi",“Avi",“Kunj"];
Syntax: var arrayname=[value1,value2.....valueN]; for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>

2. By creating instance of Array directly (using new keyword)


Syntax: var arrayname=new Array();
<script>
Ex. var i; 3. By using an Array constructor (using new keyword)
var emp = new Array();
emp[0] = "Abhi";
emp[1] = “Avi"; <script>
emp[2] = “Kunj"; var emp=new Array(“Abhi",“Avi","Shruti");
for (i=0;i<emp.length;i++){ for (i=0;i<emp.length;i++){
document.write(emp[i] + document.write(emp[i] + "<br>");
"<br>"); }
} </script>
</script>
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array properties and methods: Examples
var x = cars.length; // The length property returns the number of elements in cars
var y = cars.sort(); // The sort() method sort cars in alphabetical order

Method Description

concat() Joins two or more arrays, and returns a copy of the joined arrays

Array Object Methods: indexOf() Search the array for an element and returns its position

join() Joins all elements of an array into a string

lastIndexOf() Search the array for an element, starting at the end, and returns its position

pop() Removes the last element of an array, and returns that element

push() Adds new elements to the end of an array, and returns the new length

reverse() Reverses the order of the elements in an array

valueOf() Returns the primitive value of an array


ARRAY: Examples
Concat():Joins two or more arrays, and returns a copy of the joined arrays.
Syntax: array.concat(array1,array2…..);
Ex:
var one = ["Cecilie", "Lone"];
var two= ["Emil", "Tobias", "Linus"];
var three= ["Robin"];
var children = one.concat(two,three);

indexOf(): Searches the array for the specified item, and returns its position.
The search will start at the specified position, or at the beginning if no start position is specified, and end the search at the end of the array.
Returns -1 if the item is not found.
If the item is present more than once, the indexOf method returns the position of the first occurrence.

Syntax: array.indexOf(item); Ex:


var fruits=[“Banana”,Orange”,”Apple”,”Mango”];
var x=fruits.indexOf(“Apple”);

Here the value of x is:2 i.e. Apple is at position 2.


ARRAY: Examples
Join(): It joins the elements of an array into a string, and returns the string.
The elements will be separated by a specified separator. The default separator is comma (,).
Syntax: array.join();
Ex: var fruits=[“Banana” Orange”,”Apple”,”Mango”];
var x=fruits.join();

the result of x will be Banana,Orange,Apple,Mango.

Slice(): It returns the selected elements in an array, as a new array object.


It selects the elements starting at the given start argument, and exclude the end argument.
Syntax: array.slice (start, end);

Ex: var fruits=[“Banana”,Orange”,”Apple”,”Mango”];


var x=fruits.slice(1,3);

the result of x will be [Orange,Apple];


Arrays Operations and Properties

Declaring new empty array: var arr = new Array();

Declaring an array holding few elements: var arr = [1, 2, 3, 4, 5];

Appending an element / getting the last element:


arr.push(3);
var element = arr.pop();

Reading the number of elements (array length): arr.length;

Finding element's index in the array: arr.indexOf(1);


Date Object
This object is used to get year, month and day.

• We can use different Date constructors to create date object.


• It provides methods to get and set day, month, year, hour, minute and seconds.

Constructor:
4 variant of Date constructor to create date object:

• Date()
• Date(milliseconds)
• Date(dateString)
• Date(year, month, day, hours, minutes, seconds, milliseconds)

<html> <body> <b>Current Date and Time:</b>


<script>
Example: Current date & time
var today=new Date();
document.writeln("<br>"+today);
</script> </body> </html>
Date Object(1)

<html>
Example:
<body>
date/month/year
<b>To print date/month/year</b>
<script>
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month+"/"+year);
</script>
</body>
</html>

<html> <body> Current Time:


Example: <script>
Current Time var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.write("<br><br>"+h+":"+m+":"+s);
</script> </body> </html>
Date Object(2)

setUTCFullYear()
This method is used to set the year for the specified date on the basis of universal time.

<html>
Example: Print the
value of current &
<body>
updated year. <script>
var year=new Date();
document.writeln("Current year : "+year.getUTCFullYear()+"<br>");
year.setUTCFullYear(2019);
document.writeln("Updated year : "+year.getUTCFullYear());
</script>
</body>
</html>
Math Object

Provides several constants and methods to perform mathematical operation


<html>
Example: <body>
<script>
document.writeln("<b>SQRT=></b>"+Math.sqrt(17));
document.writeln("<b><br>RANDOM=></b>"+Math.random());
document.writeln("<b><br>POW=></b>"+Math.pow(3,4));
document.writeln("<b><br>FLOOR=></b>"+Math.floor(4.6));
document.writeln("<b><br>CEIL=></b>"+Math.ceil(4.6));
document.writeln("<b><br>ROUND=></b>"+Math.round(4.6));
document.writeln("<b><br>ABSOLUTE=></b>"+Math.abs(-4));
</script>
</body>
</html>
Number Object
It enables us to represent a numeric value.

Methods Description
isFinite() It determines whether the given value is a finite number.

isInteger() It determines whether the given value is an integer.

parseFloat() It converts the given string into a floating point number.

parseInt() It converts the given string into an integer number.

toExponential() It returns the string that represents exponential notation of the given number.

toFixed() It returns the string that represents a number with exact digits after a decimal
point.

toPrecision() It returns the string representing a number of specified precision.

toString() It returns the given number in the form of string.


Example of parseFloat() method:
<script>
var a="50";
var b="50.25"
var c="String";
var d="50String";
var e="50.25String"
document.writeln(Number.parseFloat(a)+"<br>");
document.writeln(Number.parseFloat(b)+"<br>");
document.writeln(Number.parseFloat(c)+"<br>");
document.writeln(Number.parseFloat(d)+"<br>");
document.writeln(Number.parseFloat(e));
</script>
Browser Object Model

The Browser Object Model (BOM) is used to interact with the browser

Default object of browser is window means all the functions of window can be called by specifying window or directly.

For example: window.alert(“Hello! Dear Students");


is same as: alert(“Hello! Dear Students");

Other properties (other objects) defined underneath the window object like document, history, screen, navigator, location
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.

<script>
<script>
function msg(){
function msg(){
open("http://www.kiet.edu");
setTimeout(
}
function(){
</script>
alert("Welcome to KIET-CSE after 2 seconds")
<input type="button" value=“KIET" onclick="msg()"/>
},2000);
}
</script>
<input type="button" value="click" onclick="msg()"/>
History Object

• It represents an array of URLs visited by the user.


• Allows to load previous, forward or any particular page
• It can be accessed by: window.history Or, history
1 property of history object:

No. Property Description

1 length returns the length of the history URLs.

3 methods of history object:

No. Method Description

1 forward() loads the next page.


2 back() loads the previous page.
3 go() loads the given page number.

history.back(); //for previous page


usage of history object: history.forward(); //for next page
history.go(2); //for next 2nd page
history.go(-2); //for previous 2nd page
REGULAR EXPRESSIONS
It is a sequence of characters that forms a search pattern.
The search pattern can be used for text search and text replace operations.
Syntax: /pattern/modifiers;

Example:
var patt = /Web Technology/I

• / Web Technology /i is a regular expression.


• Web Technology is a pattern (to be used in a search).
• i is a modifier (modifies the search to be case-insensitive)
Using String Methods

Regular expressions are often used with these string methods➔ search(), match() and replace().

• search(pattern) : uses an expression to search for a match, and returns the position of the match.
• replace(pattern1, pattern2) : returns a modified string where the pattern is replaced.
• match(pattern): searches for a matching pattern. Returns an array holding results, or null if not found.

Example:
var str = "Visit MySchool";
var n = str.search(/Myschool/i);
The result in n will be: 6

var str = "Visit Microsoft!";


var res = str.replace(/microsoft/i, “MySchool");
Example:
The result in res will be: Visit MySchool!
Regular Expression Modifiers

Modifiers can be used to perform case-insensitive more global searches:


Modifier Description
i Perform case-insensitive matching
g Perform a global match (find all matches rather than stopping after the first match)
m Perform multiline matching

Regular Expression Patterns


Brackets are used to find a range of characters:

Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |
Metacharacters / Token
They are characters with a special meaning:
Metacharacter / Description
Token
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning or at the end of a word

^ Match at the start of the input string

$ Match at the end of the input string

* Match 0 or more times

+ Match 0 or more times

? Match 0 or 1 times

{n} Match the string n times

\D Match anything except for digits


Cont..

Metacharacter / Description
Token
\w Match any alphanumeric character or the underscore
\W Match anything except alphanumeric characters or underscore

\S Match anything except for whitespace characters


[…] Creates a set of characters, one of which must match if the operation is to be successful. If
you need a range of characters then separate the first and last with a hypen: [0-9] or [D-G]
[^…] Creates a set of characters which doesnot match. If any character in the set matches then the
operation has failed. This fails if any lowercase letter from d to q is matched: [^d-q].

Quantifiers define quantities:


Quantifier Description

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurrences of n

n? Matches any string that contains zero or one occurrences of n


Using the RegExp Object

RegExp object is a regular expression object with predefined properties and methods.

Using test() / using exec()

• The test() method is a RegExp expression method.


• It searches a string for a pattern, and returns true or false, depending on the result.

The following example searches a string for the character "e":

Example
var patt = /e/;
patt.test("The best things in life are free!");
(or)

/e/.test("The best things in life are free!")

Since there is an "e" in the string, the output of the code above will be: true
Global Property of RegExp
• It is a read-only boolean property of RegExp objects.
• It specifies whether a particular regular expression performs global matching, i.e., whether it
was created with the "g" attribute.
Syntax: RegExpObject.global
Returns "TRUE" if the "g" modifier is set, "FALSE" otherwise.

<html> <body> <script>


var re = new RegExp( "string" );
if ( re.global ){
document.write("Test1 - Global property is set");
Example: }else{
document.write("Test1 - Global property is not set"); Output:
}
Test1 - Global property is not set
re = new RegExp( "string", "g" ); Test2 - Global property is set
if ( re.global ){
document.write("<br />Test2 - Global property is set");
}else{
document.write("<br />Test2 - Global property is not set");
}
</script></body></html>
lastIndex Property of RegExp

• It is a read/write property of RegExp objects.


• For regular expressions with the "g" attribute set, it contains an integer that specifies the character
position immediately following the last match found by the RegExp.exec() and RegExp.test() methods.
• These methods use this property as the starting point for the next search they conduct.

<html>
<body>
<script>
Example: var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
re.test(str);
document.write("Test 1 - Current Index: " + re.lastIndex); Output
re.test(str); Test 1 - Current Index: 10
document.write("<br />Test 2 - Current Index: " + re.lastIndex); Test 2 - Current Index: 35
</script>
</body>
</html>
FORM VALIDATION USING REGULAR EXPRESSION
Validation checks Expression Result Code
Checking for all /^[a-zA-Z]$/ If the entered characters is not in var alphaExp = /^[a-zA-Z]$/;
Letters(only alphabets) lower case or upper case, it will if(inputtext.value.match(alphaExp)){
return false. return true;
}else{……………….
Checking for all numbers /^[0-9]$/ If string value is numeric, it will var numericExpression = /^[0-9]$/;
return true if(inputtext.value.match(numericExpression)){
return true;
}else{…………..
Checking for all numbers /^[0-9a-zA- If entered things includes numbers var alphaExp = /^[0-9a-zA-Z]$/;
and letters Z]$/ and alphabetic character or not if(inputtext.value.match(alphaExp)){
return true;
}else{…………

Checking for Password:


Password supports special characters and here min length 6 max 20 charters:
var ck_password = /^[A-Za-z0-9!@#$%^&*()_]{6,20}$/;

Checking for Phone:


Numbers only 10 digits.
var ck_phone = /^[0-9]{10}$/;
Email Validation
• @compem.net [no character before@]
Wrong email address: • Lime!gear@demon.com [invalid character!]
• sunshine@mode_bright.com [underscore are not allowed in the domain name]

Valid email address should contain:


• The combination of letters, numbers, periods, plus sign, and /or underscores.
• The @symbol.
• Combination of letters, numbers and periods.
• The top level domain. (com, net, org, us, gov)

A general expression to check valid email address is: /^[w-.+]+@[a-zA-Z0-9.]+.[a-zA-Z0-9]{2,4}$/


➢ The expression checks the letters, numbers, and other symbol at a proper sequence.
➢ The sequence is defined as: [alphabets/numbers/underscore/plus sign-@-alphabets/numbers/periods.domain name]
➢ If the entered email address is not in a proper sequence, then the message will popup which says “Wrong Email Address”.

function emailValidation(inputtext, alertMsg) {


var emailExp = /^[w-.+]+@[a-zA-Z0-9.-]+.[a-zA-z0-9]{2,4}$/;
if (inputtext.value.match(emailExp)) {
return true;
} else {
document.write(alertMsg); // displays validation rule for email.
inputtext.focus();
return false;
Automatic HTML Form Validation
• HTML form validation can be performed automatically by the browser:
• Using “required” attribute
• If a form field (fname) is empty, the required attribute prevents this form from being submitted:

<html>
<body>
<form action="" method="post">
Example: <input type="text" name="fname" required><br><br>
<input type="text" name="lname" required><b>
<input type="submit" value="Submit">
</form
<p>If you click submit, without filling out the text field,
your browser will display an error message.</p>
</body> </html>

OP:
Thank
You

You might also like