KEMBAR78
Javascript | PDF | Dynamic Web Page | Java Script
0% found this document useful (0 votes)
8 views85 pages

Javascript

Uploaded by

hack99856
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views85 pages

Javascript

Uploaded by

hack99856
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 85

UNIT I-JavaScript

Client-side scripting:
 Run in the client browser and process requests without call backs to the server
 client-side scripting (JavaScript) benefits
 usability: can modify a page without having to post back to the server (faster UI)
 efficiency: can make small, quick changes to page without waiting for server
 event-driven: can respond to user actions like clicks and key presses

Server-side scripting:
 server-side programming (PHP,servlets,JSP,..) benefits:
 security: has access to server's private data; client can't see source code
 compatibility: not subject to browser compatibility issues
 power: can write files, open connections to servers, connect to databases, ...
SERVER-SIDE SCRIPTING CLIENT-SIDE SCRIPTING

Works in the back end which could not be visible at the Works at the front end and script are visible among the
client end. users.

Processing Requires server interaction. Does not need interaction with the server.

PHP, servlets,JSP,AS>NET JavaScript, VB Script etc.

Could effectively customize the web pages and provide Can reduce the load to the server.
dynamic websites.

Relatively secure. Insecure


JavaScript Language
 JavaScript was introduced by Brendan Eich, a member in Netscape2 group, in early 1996 to provide
dynamicity and interactivity to webpages.
 During the development phase it was known as Mocha, later as LiveScript
 When it was released, it as renamed as JavaScript.
 Javascript is a scripting language most often used for client-side web
development.
 JavaScript
--is a lightweight scripting language
--used to make web pages interactive
--insert dynamic text into HTML
--reacts to events
--dynamic drop-down menus
--get information about client browser
--form validation etc.
JavaScript vs Java
 The JavaScript programming language is developed by Netscape, Inc and not part of the Java
platform.
 Java applications are run in a virtual machine or web browser while JavaScript is run on a web
browser.
 Java code is compiled whereas while JavaScript code is interpreted by web browser.
 JavaScript is a scripting language, whereas Java is a programming language.

Applications of JavaScript
 Client side validation
 Manipulating HTML Pages
 User notifications
 Back-end data loading
 Presentations
There are two ways to insert JavaScript code into an HTML code
1) Internal JavaScript:
JavaScript code can be inserted either in head or body section of HTML using <script> tag.
<script type=“text/JavaScript” language=“JavaScript”>
Java Script Code
</script>

2) External JavaScript:
We can create external JavaScript file with .js extension and embed it in many html pages.
<script type=“text/JavaScript” language=“JavaScript” src=”js file path”>
Java Script Code
</script>

-JavaScript is a case-sensitive langage.


-JavaScript comments:
Comments are of two types:
1)Line comment-a line comment starts with //
Example-//this is a line comment
2) Block comment-block comment starts with /* and ends with */
Example-
/* this is block comment
this will also be ignored
*/
Javascript Example
Internal java Script External java Script
<html> <html>
<body> <head>
<script language="javascript"> <script type="text/javascript"
document.write("JavaScript is a simple language "); src="message.js"></script>
</script> </head>
</body> <body>
</html> <p>Welcome to JavaScript</p>
<form>
<input type="button" value="click"
onclick="msg()"/>
</form>
</body>
</html>

message.js

Note: The document.write() function is used to display function msg(){


dynamic content through JavaScript. alert("Hello ,Welcome to VJIT");
}
Program1:
<html>
<head>
<script language=“JavaScript” type = "text/javascript">
//function declaration
function hello()
{
document.writeln("Hello World");
}
</script> </head>
<body>
<script language=“JavaScript” type = "text/javascript">
//function call
hello();
//other javascript statements
</script>
</body>
</html>
Declaring Variables
• JavaScript variables are containers for storing data values.
• Javascript variables are not specified, variables are declared with “var” keyword.
• Javascript variables are different from other variables in the sense that they are un-typed.
Naming conventions:
The general rules for constructing names for variables are:
 The name of a variable cannot be a keyword.
 It must start with a letter or an underscore followed by zero or more letters,underscores or digits.
 White spaces,punctuation characters such as commas,full stop etc are not allowed.
 Some new browers allow variable names to start with ‘$’ sign, but it is not recommended to use $ at
the beginning of a variable name to avoid incompatibility.
Scope of variables
 Scope in JavaScript refers to the current context of code, which determines the accessibility of
variables to JavaScript.
 The two types of scope are local and global.
1) Local variables
These are declared within a function or a block.
Syntax: var variable=value;

The keyword var specifies that the variable is a local variable and is visible within the scope in which it
is declared.
Examples: var sum=0; //number
var msg=“hello world”; //string
var found=false; //boolean
Example:
2) Global variables
<!DOCTYPE html>
A global variables is created without the keyword <html>
var. <body>
It is created by assigning a value to it. <h2>JavaScript Variables</h2>
Syntax: variable=value; <p>In this example, x, y, and z are variables.</p>
Examples: x=1; <script type=“text/JavaScript”>
lang=“JavaScript”; var x = 10;
flag= true; var y = 20;
These variables are created as soon as the block is var z=x+y;
executed and become visible from that instant. document.write(z);
</script>
</body>
</html>
Undefined variables:
 A variable declared without a value will have the value undefined.
 The variable carName will have the value undefined after the execution of this
statement:
Example: var carName;

Re-declaring JavaScript variables:


 If you re-declare a JavaScript variable, it will not lose its value.
 The variable carName will still have the value "Volvo" after the execution of these statements:
Example:
var carName = "Volvo";
var carName;
JavaScript Popup Boxes
JavaScript has three kinds of popup boxes:
 Alert box,

 Confirm box, and

 Prompt box.

Alert Box:
 An alert box is often used if you want to make sure information comes through to the user.
 When an alert box pops up, the user will have to click "OK" to proceed.
window.alert("sometext");
Confirm Box
 A confirm box is often used if you want the user to verify or accept something.
 When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
 If the user clicks "OK", the box returns true.
 If the user clicks "Cancel", the box returns false.

window.confirm("sometext");

Prompt Box
 A prompt box is often used if you want the user to input a value before entering a page.
 The user will have to click either "OK" or "Cancel" to proceed after entering an input value.
 If the user clicks "OK" the box returns the input value.
 If the user clicks "Cancel" the box returns null.

window.prompt("sometext","defaultText");
Functions
 A JavaScript function is a block of code designed to perform a particular task.
 A function is a set of statements that performs some tasks or does some computation and then returns the
result to the user.
 A JavaScript function is executed when "something" invokes it (calls it).
 A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
 Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
 The parentheses may include parameter names separated by commas:(parameter1, parameter2, ...)
 The code to be executed, by the function, is placed inside curly brackets: {}
Syntax:
function name(parameter1, parameter2, parameter3)
{
// code to be executed
}
 The code inside the function will execute when "something" invokes (calls) the function:
--When an event occurs (ex: when a user clicks a button)
--When it is invoked (called) from JavaScript code
--Automatically (self invoked).
• A function must be declared before it is called, this is applicable for variables also.
-It means javascript functions and declare global variables within the head section.
-Other javascript statements, including function calls, can be placed anywhere within the body tag.

Example:
var x = myFunction(4, 3); // Function is called, return value will end up in x

function myFunction(a, b)
{
return a * b; // Function returns the product of a and b
}
Example:
<html>
<head>
<script type=“text/JavaScript”>
function func1()
{
document.write("This is simple function");
}
</script>
</head>
<body>
<h3>Functions</h3>
<input type="button" onclick="func1()" value="click">
</body>
</html>
Note: The onclick event occurs when the user clicks on an element.
Example: Example:
<html> <html>
<head>Javascript</head> <head>Javascript</head>
<body> <body>
<h3>Passing parameters</h3> <h3>Functions</h3>
<script> <script>
function mul( a , b){ var x = myFunction(4, 6);
return a*b;
} function myFunction(a, b)
document.write(mul(12,13)); { return a * b;
</script> }
</body> document.write(x);
</html> </script>
</body>
</html>
Program 2:

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h2>JavaScript in Head</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>


</body>
</html>
Example: popup.html

<!DOCTYPE html> function func2()


<html> {
<body bgcolor=“pink”> window.confirm("Do u want to continue");
<h2>JavaScript Pop up windows</h2>
}
<script>
function func1() </script>
{ <form name="f1">
var a=document.f1.t1.value; Username:<input type="text" name="t1"><br>
var x=document.f1.t2.value; Lastname:<input type="text" name="t2"><br>
if (a== null || a == "") <input type="button" value="login"
{ onclick="func1()">
window.alert("enter username");
<input type="button" value="confirm"
}
onclick="func2()">
else if(x=="")
{ </form>
window.alert("enter lastname"); </body>
} </html>
else
{
document.write("hello user");
} }
Arrays
 JavaScript arrays are used to store multiple values in a single variable.
 An array is a special variable, which can hold more than one value at a time.
Syntax: var arrayname=[value1,value2.....valueN]; //values are contained inside [ ] and separated by ,

<!DOCTYPE html>
<html>
<head></head>
<body>
<h4>Simple Arrays</h4>
<script type="text/JavaScript">

var fruits=["orange","mango","apple"];
for (i=0;i<fruits.length;i++)
{
document.write(fruits[i] + "<br/>");
}
</script>
</body>
</html>
Using the JavaScript Keyword new/Using constructor
 new keyword is used to create instance of array.
 There is no need to use the JavaScript's built-in array constructor new Array().
var points = new Array(); // Bad
var points = []; // Good

 The following example also creates an Array, and assigns values to it:
var points = new Array(40, 100, 1, 5, 25, 10); // Bad
var points = [40, 100, 1, 5, 25, 10]; // Good
The new keyword only complicates the code. It can also produce some unexpected results.
Example: var fruits=new Array();
fruits[0]=“apple”;
fruits[1]=“orange”;
fruits[2]=“mango”;
Array methods

1)concat( )-It returns a new array object that contains two or more merged arrays.
var res=array.concat(arr1,arr2,....,arrn) ;
2)indexOf( )-It searches the specified element in the given array and returns the index of the first match.
var n=array.indexOf(element,index) ;
3)join( )-It joins the elements of an array as a string.
var res=array.join(separator) ;// default separator is ,
4)lastIndexOf( )-It searches the specified element in the given array and returns the index of the last
match.
var n=array.lastIndexOf(element,index);
Example Program:
<html>
var arr4=["C","C++","Python","C+
<body> +","Java"];
<script>
var arr1=["C","C++","Python"];
var arr2=["Java","JavaScript","Android"];
var result= arr4.lastIndexOf("C+
+");
var result=arr1.concat(arr2); document.writeln("last index
document.writeln("concatination:”+result+"<br>");
of c++: "+result+"<br>");
var arr=["C","C++","Python","C++","Java"];
var result= arr.indexOf("C++");
</script>
document.writeln("index of C++: "+result+"<br>");
</body>
var arr3=["PhP","Servlets","JSP"] </html>
var result=arr3.join(" ")
document.write("joins the elements as a string:
"+result+"<br>");
9) unshift()-It adds one or more elements in the
5) pop( )-It removes and returns the last element of an
beginning of the given array.
array.
array. unshift(e1,e2,....,en);
var x=array.pop() ;

10) slice( )-It returns a new array containing the copy of


6) push( )-It adds one or more elements to the end of an
the part of the given array.
array.
array.slice(start,end) ;
array.push(element1,element2....elementn);

11) sort( )-It returns the element of the given array in a


7) splice( )-It add/remove elements to/from the given
sorted order.
array.
array.sort();
array.splice(start,delete,element1,element2,…..,
elementn) ;
12) reverse( )-It reverses the elements of given array.
8) shift( )-It removes and returns the first element of an array.reverse()
array.
var n=array. shift(); 13) delete( )-elements can be deleted by using the
JavaScript operator delete.
delete array[index];
Example-The splice() method can be used to add new items to an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
The first parameter (2) defines the position where new elements should be added (spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.

Example-
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");
Output: Banana,Orange,Lemon,Kiwi

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1); // Removes the first element of fruit
Output: Orange,Apple,Mango
Program: var result=arr.slice(0,2);
document.writeln("slice: "+result+"<br>");
<html>
<body> var arr=[2,4,1,8,5];
<script> var result=arr.sort(); //1,2,4,5,8
var arr=["AngularJS","Node.js","JQuery"]; document.writeln("sorted array:
document.writeln("Orginal array: "+arr+"<br>");
"+result+"<br>");
document.writeln("Extracted element: "+arr.pop() document.writeln("element at first
+"<br>"); place:"+result[0]+"<br>");
document.writeln("Remaining elements: "+ arr+"<br>");

arr.push("PhP");
var
document.writeln("Remaining elements: "+ arr+"<br>"); arr=["Monday","Tuesday","Thursday","Fri
day"];
var rev=arr.reverse(); var result=arr.splice(2,0,"Wednesday")
document.writeln("reverse of arr is: "+rev+"<br>"); document.writeln(arr);
var result=arr.shift();
document.writeln(result+"<br>"); </script>
</body>
var result=arr.unshift("J2EE");
</html>
document.writeln(arr+"<br>");
Strings
String is an object that represents a sequence of characters
2 ways to create string in JavaScript
var stringname="string value";
var stringname=new String("string literal");
String Methods 5) lastIndexOf( )-It provides the position of a char value
present in the given string by searching a character
1) charAt( )-It provides the char value present at the
from the last position.
specified index.
var n=lastIndexOf(ch[,position]);
var c=String.charAt(index);
var n=lastIndexOf(str[,position]);

2) charCodeAt( )-It provides the Unicode value of a


6) toUpperCase( )-It converts the given string into
character present at the specified index.
uppercase letter.
var uc=string.charCodeAt(index);
var str=string.toUpperCase();

3) concat( )- It provides a combination of two or more


7) toLowerCase( )-It converts the given string into
strings.
lowercase letter.
var new_str=string.concat(str1,str2,...,strn); var str=string.toLowerCase();

4) indexOf( )-It provides the position of a char value 8) search( )- It searches a specified regular
present in the given string. expression in a given string and returns its
var n=indexOf(ch[,position]) position if a match occurs.
var n=indexOf(str[,position]) string.search(regexp);
9) match( )-It searches a specified regular expression in a 13) toString()-It provides a string
given string and returns that regular expression if a representing the particular object.
match occurs. object.toString();
string.match(regexp);

10) replace()-It replaces a given string with the specified


replacement.
string.replace(current string,new string);

11) substr()-It is used to fetch the part of the


given string on the basis of the specified
starting position and length.
string.substr(start,length);

12) slice()-It is used to fetch the part of the


given string. It allows us to assign positive
as well negative index.
string.slice(start,end);
Program:
<html>
<body bgcolor=“pink”>
<h3>String Methods</h3>
<script>

var str="JavaScript";
document.writeln("char value present at index-"+str.charAt()+"<br>");//print first character
document.writeln("unicode value of character "+str.charCodeAt(3)+"<br>");

var x="vidya ";


var y=" Jyothi";
var z=" Inst. "
document.writeln("combination of strings x,y,z "+x.concat(y,z)+"<br>");

var web="Learn JavaScript on Javaworld";


document.write("index of character "+web.indexOf('a')+"<br>");
document.write("index of string java "+web.indexOf("Java")+"<br>");

var str1="JavaScript is a Scripting language. Scripting languages are often interpreted";


var str2=str.search("Scripting");
document.writeln("search position of string"+str2+"<br>");
var str3="Javascript";
document.writeln("match string "+str3.match(/a/g)+"<br>");

var str4="JavaScript";
document.writeln("substring "+str4.substr(1,4)+"<br>");

var str5 = "JavaScript";


document.writeln("slice the part of string "+str5.slice(2,4));
</script>
</body>
</html>
JavaScript Objects
 A JavaScript object is an entity having state and behavior (properties and method). For example: car, pen, bike,
chair, glass, keyboard, monitor etc.
 JavaScript is an object-based language. Everything is an object in JavaScript.
 An object is a collections of properties and methods
 Properties represents features
 Methods represents actions that may be performed upon these objects
 In JavaScript properties and methods can be added at any time event after the creation of an object.
 Objects of the same class may have different sets of properties and methods
Creating Objects in JavaScript

There are 3 ways to create objects.


 By object literal
 By creating instance of Object directly (using new keyword)
 By using an constructor function (using new keyword)
Javascript object Using object literal:
 Using an object literal, you can define and create an object in one statement.
 An object literal is a list of name:value pairs inside curly braces .
syntax: Obj_name={property1:value1, property2:value2, …….. propertyn:valuen};
Ex: p={x:2,y:4};

 Once an object is created its properties are accessed using dot(.) operator
Obj_name.propertyName;
Ex: p.x or p.y

 We can add new properties for objects


Obj_name.new_prop_Name=value;
Ex: p.color=“red”;

Examples: Circle={x:2,y:3,r:10};
aCircle2={center:{x:2,y:3},r:10};
stud={name:”xyz”,id:501,marks:{85,90,89,88}};
Javascript object by using instance of object/object constructor:
In Javascript ,we can create empty objects by using Object constructor and new operator

Syntax: var objectname=new Object();


Example:
<html>
Ex: var obj=new Object(); // empty object <body>
obj.x=20; <script>
obj.y=30;// adding properties var emp=new Object();
emp.id=101;
emp.name="Rani Kavitha";
emp.salary=50000;
document.write(emp.id+" "+emp.name+"
"+emp.salary);
</script>
</body>
</html>
Output: 101 Rani Kavitha 50000
Javascript object by using an Constructor function:

Here, you need to create function with arguments. Each argument value can be assigned in the current object by
using this keyword.
 In JavaScript a class is defined by a function , which acts as the constructor for the class.
 Objects are created with the help of this constructor function and new operator.
 Ex: The following is the class definition for the class Point
function Point(){
}
p= new Point(); or p=new Point;
p.x=20;
p.y=30;
 Parameterized constructor is used to add some  Properties may be added per-object basis
common properties and set their values. Obj_name.new_prop_name=value;
 Other properties may be added latter on a per-object Ex: p1.color=“red”;
basis as well as per-class basis, as and when needed.
 The this keyword refers to the current  Properties may be added per-class basis
object.
class_name.prototype.new_prop_name=value;

function Point(x,y)
Ex: p1.prototype.color=”green”;
{
this.x=x;
this.y=y;
}
Cretae objects:
p1=new Point(10,20);
P2=new Point(100,200);
Example: Example:

<html>
<html> <body>
<script>
<body>
function emp(id,name,salary){
<script> this.id=id;
emp={id:102,name:“Rani",salary:40000} this.name=name;
this.salary=salary;
document.write(emp.id+" "+emp.name+"
}
"+emp.salary); e=new emp(103,"Kavitha",30000);
</script>
document.write(e.id+" "+e.name+" "+e.salary);
</body>
</script>
</html> </body>
</html>

Output: Output:
102 Rani 40000 103 Kavitha 30000
Adding New methods:
It is a two step process:
 Define the Function
 Associate it within the constructor during object creation or make this association later.
Ex:
function carea()
{
return 3.14159*this.r*this.r;
}
function Circle(x,y,r){
this.x=x;
this.y=y;
this.r=r;
this.area=carea;
}
//Once the function carea is associated with the property area,it may be called as follows:
var c=new Circle(1,2,3);
var result=c.area();
Objects as Associative Arrays
 Property of an object is usually accessed using the dot operator
Obj.prop_name;
 JavaScript allows us to access the property of an object using the array notation as follows:
Obj_name[‘propertyname’]
Ex: if x is property of object p, It is accessed as p[‘x’]
Built-in objects/Predefined objects
 Javascript provides built-in objects such as Array,Date,Math,String Objects

 Javascript allows us to access contents of web pages with the help of DOM(DocumentObject
Model) objects such as window object,location object,history object,navigator object,document
object.
Date Objects:
 Date objects are created with the new and Date() constructor.
Date()
Date(year, month, day, hours, minutes, seconds, milliseconds)
Date(milliseconds)
Date(date string) Method Description
getFullYear() Get the year as a four digit number (yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number (1-31)
getHours() Get the hour (0-23)
getMinutes() Get the minute (0-59)
getSeconds() Get the second (0-59)
getMilliseconds() Get the millisecond (0-999)
getTime() Get the time (milliseconds since January 1,
1970)
getDay() Get the weekday as a number (0-6)
Date.now() Get the time. ECMAScript 5.
Method Description
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and
day)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since
January 1, 1970)
Math Object:
 Math object allows you to perform mathematical tasks on numbers.
ex: Math.PI
Math.round(4.7) Method Description
abs(x) Returns the absolute value of x
ceil(x) Returns the value of x rounded up to its nearest integer
cos(x) Returns the cosine of x (x is in radians)
floor(x) Returns the value of x rounded down to its nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x, y, z, ..., n) Returns the number with the highest value
min(x, y, z, ..., n) Returns the number with the lowest value
pow(x, y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Returns the value of x rounded to its nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle
RegularExpressions:
 A regular expression is an object that describes a pattern of characters that specifies a rule.
 Regular expressions are used to perform pattern-matching , search and replace functions on
text.
 Regular expression using a literal
 var exp=/pattern/flags;
 Regular expression using a constructor
 var exp=new RegExp(“pattern”,”flags”);

Flags:
 icase-insensitive matching
 gPerform a global match
 mPerform multiline matching
Metacharacters:
 Meta characters are characters with a special meaning.
 These are used while creating patterns for Regular expressions

. Find a single character, except newline or line terminator


\w Find a word character(alphanumeric)
\W Find a non-word character
\d Find a digit
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
\b Find a match at the beginning/end of a word, beginning like this: \bHI, end like this:
HI\b
\B Find a match, but not at the beginning/end of a word
\0 Find a NULL character
\n Find a new line character
[] Find any of the character inside the brackets
| Find any of the alternatives between x or y separated with |
() Groups parts of the context expression
$ indicates end of the expression
[^ ] Find any character NOT between the brackets

Quantifiers
+ one or more occurences
* Zero or more occurences

? Zero or one occurences


RegExp functions
 exec() Tests for a match in a string.
RegExpObject.exec(string)
Returns the first match, if not returns null

 test() Tests for a match in a string.


RegExpObject.test(string)
returns true if it finds a match, otherwise it returns false
<html>
<head></head>
<body>
document.write("string matching
<h3>Regular expression functions</h3> using exec function:
<script language="JavaScript"> "+result+"<br>"+result2+"<br
>");
var str = "Hello world!";
document.write("string matching
// look for "Hello" using test function:
var patt = /Hello/g; "+result3+"<br>"+result4);
var result = patt.exec(str);
var re=/e/;
</script>
</body>
var result3= re.test("Hello world");

</html>
// look for “HTML"
var patt2 = /HTML/g;
result2 = patt2.exec(str);
result4 = patt2.test(str);
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Regular Expressions</h2>

<p>Search a string for "JavaScript", and display the position of the match:</p>

<script>
var str = "Know about Javascript! javascript";
var s=str.search(/JavaScript/i);
document.write("searching pattern string "+s+"<br>");

var n = str.match(/JavaScript/ig);
document.write("pattern matching string "+n);
</script>
Example:

</script>
<html>
<head> </head>
<script language="JavaScript"> <body>
function myFunction() { <p>Do a global search, and test for "Hello"
var str = "Hello world!";
and "W3Schools" in a string:</p>
// look for "Hello"
var patt = /Hello/g; <button onclick="myFunction()">Try
var result = patt.exec(str); it</button><br>
var result3= patt.test(str); Using exec()
// look for “HTML"
<p id="demo"></p>
var patt2 = /HTML/g;
result2 = patt2.exec(str); Using test()
result4 = patt2.test(str); <p id="demo2"></p>
document.getElementById("demo").innerHTML = result
+ "<br>" + result2;
document.getElementById("demo2").innerHTML = result3
</body>
+ "<br>" + result4; </html>
}
JavaScript HTML DOM
 Javascript allows us to access contents of web pages.
 The components of web page are represented by objects that are organized in hierarchical structure
called Document Object Model(DOM)
 These objects have properties and methods that can be used to work with web pages.

Window Object:
 It represents the browser's window.
 All global JavaScript objects, functions, and variables automatically become members of the
window object
 Global variables are properties of the window object
 Global functions are methods of the window object
 Even the document object (of the HTML DOM) is a property of the window object.
Method Description
alert(msg) displays the alert box containing message with ok button.
confirm(msg) displays the confirm dialog box containing message with ok and
cancel button.
prompt(msg,[input]) 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.
blur() Removes focus from the window
focus() Gives focus to this window
stop() Stops the current download
moveTo(x,y) Moves the window to the specified screen coordinates
resizeTo(x,y) Resizes an entire window to the specified outer height and width
Example
<!DOCTYPE html>
<html>
<body>
<h2>The window Object</h2>
<script>
function f1()
{
window.open(“simple.html”);
}
function msg(){
alert("Hello Alert Box");
}
function msg1(){
confirm("Do u want to proceed");
}
</script>
</body>
<input type=button value="open" onclick="f1()">
<input type=button value="click" onclick="msg()">
<input type=button value="confirm" onclick="msg1()">
Location Object:
Location encapsulates the current URL that is displayed in the visitors browser.
Properties in location object are
 location object can be used to get the current page address (URL)
 href returns the href (URL) of the current page
 hostname returns the domain name of the web host
 pathname returns the path and filename of the current page
 protocol returns the web protocol used (http: or https:)
 assign() loads a new document

Methods:
reload() : current URL is reloaded,equivalent to pressing browsers refresh button
replace(URL) :loads the specified URL by replacing current one

Ex: location.replace(http://www.google.com);
location.reload();
<!DOCTYPE html>
<html>
<body>
<h3>The window.location object properties</h3>
<script>
document.write("The full URL of this page is:<br>" + window.location.href+"<br>");
document.write("Page hostname is " + window.location.hostname+"<br>");
document.write("Page path is " + window.location.pathname+"<br>");
document.write("Page protocol is " + window.location.protocol+"<br>");
</script>
</body>
History object:
window.history object contains the browsers history.

Methods
 history.back() method loads the previous URL in the history list.
 history.forward() method loads the next URL in the history list.
 history.back() - same as clicking back in the browser
 history.forward() - same as clicking forward in the browser
<html>
<head>
<script>
function goForward() {
window.history.forward()
}
function goBack() {
window.history.back()
}
</script>
</head>
<body>
<input type="button" value=“Forward" onclick="goForward()">

<input type="button" value="Back" onclick="goBack()">

</body>
</html>
Navigator object:
window.navigator object contains information about the visitor's browser.
 navigator.appName-returns the application name of the browser
 navigator.appCodeName-returns the application code name of the browser
 navigator.platform-returns the browser platform (operating system)
 navigator.product property returns the product name of the browser engine(Most browsers returns
"Gecko" as product name)
 navigator.appVersion property returns version information about the browser
 navigator.cookieEnabled property returns true if cookies are enabled, otherwise false
<!DOCTYPE html>
<html>
<body>
<h2>The Navigator Object</h2>
<script>
document.write("navigator.cookieEnabled is " + navigator.cookieEnabled+"<br>");
document.write("navigator.appName is " + navigator.appName+"<br>");
document.write("navigator.appCodeName is " + navigator.appCodeName+"<br>");
document.write("navigator.product is " + navigator.product+"<br>");
</script>
</body>
</html>
Document object
The HTML DOM document object is the owner of all other objects in your web page.
 The document object represents your web page.
 If you want to access any element in an HTML page, you always start with accessing the document object.
 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.

Properties of document object:


The properties of document object that can be
accessed and modified by the document object.
Methods of document object
Method Description
write("string") writes the given string on the document.
writeln("string") writes the given string on the document with newline
character at the end.
getElementById() returns the element having the given id value.
getElementsByName() returns all the elements having the given name value.
getElementsByTagName( returns all the elements having the given tag name.
)
getElementsByClassNam returns all the elements having the given class name.
e()
Accessing field value by document object:

In this example, we are going to get the value of input text by user. Here, we are using document.form1.name.value to get the value of name field.
Here, document is the root element that represents the html document.form1 is the name of the form.name is the attribute name of the input
text.value is the property, that returns the value of the input text.

<!DOCTYPE html>
<html>
<body>
<h3>Accessing field value by document object</h3>
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/><br>
<input type="button" onclick="printvalue()" value="print name"/>
</form>

</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h3>Methods of document object</h3>
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
document.write(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form> 64
</body>
</html>
Javascript Events:

--Javascript identifies an event and takes an action by executing some piece of code.The procedure of
taking actions is called event handling.
--The specific javascript code that takes the action(i.e.,handles the event) is called event handler.
--An event handler may be any valid javascript statement,the handler of an event is usually provided as a
function.
Examples of HTML events:
 When a user clicks the mouse
 When a web page has loaded
 When an image has been loaded
 When the mouse moves over an element
 When an input field is changed
 When an HTML form is submitted
 When a user strokes a key
Mouse Events
Event name Event handler(property used for Description
event)
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.

Window/Document events
Event name 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
Form events

Event name Event handler Description


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

Keyboard events

Event name Event handler Description


Keydown & onkeydown & onkeyup When the user press
Keyup and then release the
key
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
function clickevent()
{
document.write("This is mouse events");
}
</script>
<form>
<input type="button" onclick="clickevent()" value="click">
</form>
</body>
</html>

Examples:
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
<input type="text" id="input1" onfocus="focusevent()"/>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<body onload="window.alert('Page successfully loaded');">
DHTML/Dynamic HTML with javascript

 DHTML stands for Dynamic HyperText Markup language.


 Dynamic HTML is not a markup or programming language but it is a term that combines the
features of various web development technologies for creating the web pages dynamic and
interactive.
 DHTML includes HTML, CSS and Javascript to make a page dynamic.

 All of these are linked through DOM(Document Object Model).


 DOM is the interface that allows scripting languages to access the content,style and structure
of the web documents and change them dynamically.
Form validation
 It is important to validate the form submitted by the user

because it can have inappropriate values. So validation is


must.
 The JavaScript provides you 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 JavaScript
form validation.
 we can validate name, password, email, date, mobile number

etc fields.
Example: Simple Form validation
<html>
<body>
<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=“simple.html"
onsubmit="return validateform()" >
Name: <input type="text" name="name"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="register">
</form>
</body>
</html>
JavaScript Can Validate Numeric Input: // If x is Not a Number or less than one or
<!DOCTYPE html> greater than 10
<html> if (isNaN(x) || x < 1 || x > 10) {
<body bgcolor=“pink”>
text = "Input not valid";
<h2>JavaScript Can Validate Input</h2>
<p>Please input a number between 1 and 10:</p>
} else
<input id="numb"> {
<button type="button" text = "Input OK";
onclick="myFunction()">Submit</button> }
document.getElementById("demo").innerHTML
<p id="demo"></p>
= text;
<script>
}
function myFunction() {
var x, text; </script>
</body>
// Get the value of the input field with </html>
id="numb"
x = document.getElementById("numb").value;
Automatic HTML form validation: If a form field (fname) is empty, the required attribute prevents this form
from being submitted

<!DOCTYPE html>
<html>
<body>
<h3>Automatic Form validation</h3>
<form action=“simple.html" method="post">
<input type="text" name="fname" required>
<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>
If we click submit without filling text field it displays as below

If the text field is filled and when clicks on submit it redirects to linked file
Program: Validating the Registration form using Regular expressions
<html>
<head><h1>Form validation using Regular expression</h1>
<script>
function validateform(){
var usr=/^[A-Za-z]\w{7,14}$/;
var name1=document.myform.name.value;
var pwd=/\w{7,14}$/;
var pwd1=document.myform.password.value;
if (!usr.test(name1)){
alert("name should not be empty ,should start with alphabets and length should be 7 to 14 only");
return false;
}
if(!pwd.test(pwd1))
{
alert("enter correct password");
return false;
}
document.write("registered successfully");
}
</script>
</head>
<body>
<form style="font-size:30px" name="myform" method="post" onsubmit="return
validateform()" >
Name: <input type="text" name="name"><br>
Password: <input type="password" name="password" required><br>
<input style="font-size:30px" type="submit" value="register">
</form>
</body>
</html>

You might also like