JavaScript (Unit-3) Part 1
JavaScript (Unit-3) Part 1
• 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
• 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.
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()
– confirm(msg) Display a message in a dialog box with two buttons: "OK" or "Cancel".
- 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):
<script>
Example: var x = 10; Output:
var y = 20;
30
var z=x+y;
document.write(z);
</script>
<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
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
• if...else statement - to execute some code if the condition is true and another code if the condition is false
<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 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.
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:
mouseover onmouseover When the cursor of the mouse comes over the element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
change onchange When the user modifies or changes the value of a form element
EVENTS- Event Handlers(3)
(4) Window/Document events:
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)
<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>
catch {} statement executes only after the execution of the try {} statement.
Also, one try block can contain one or more catch blocks.
<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 HTML DOM is a standard object model and programming interface for HTML. It defines:
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
DOM(5)
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
<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">
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
<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.
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)
✓ 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.
<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>
<script>
Ex. function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(102,“Shruti Pathak",60000);
• 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>
<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
<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) 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.
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
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
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.
Constructor:
4 variant of Date constructor to create date object:
• Date()
• Date(milliseconds)
• Date(dateString)
• Date(year, month, day, hours, minutes, seconds, milliseconds)
<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>
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
Methods Description
isFinite() It determines whether the given value is a finite 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.
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.
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.
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
Example:
var patt = /Web Technology/I
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
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 0 or 1 times
Metacharacter / Description
Token
\w Match any alphanumeric character or the underscore
\W Match anything except alphanumeric characters or underscore
RegExp object is a regular expression object with predefined properties and methods.
Example
var patt = /e/;
patt.test("The best things in life are free!");
(or)
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>
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{…………
<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