0% found this document useful (0 votes)
22 views79 pages

Javascript 11

Uploaded by

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

Javascript 11

Uploaded by

verifiednot162
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

What is JavaScript?

❑ A lightweight programming language ("scripting language")


❑ Used to create interactive user interface in a web page (e.g., menu, pop-up alert, windows,
etc.)
❑ Manipulating web content dynamically
• Change the content and style of an element
• Replace images on a page without page reload
• Hide/Show contents
• Manipulating web content dynamically
❑ Dynamically access and update the content, structure, and style of a Web page.
❑ Event Driven Programming (ex: page load user click)
❑ Get information about a user's computer (ex: browser type)
❑ Perform calculations on user's computer (ex: form validation)
❑ Different brands or/and different versions of browsers may support different implementation of
JavaScript.
❑ JScript is the Microsoft version of JavaScript.
1
Advantages of JavaScript
Speed : JavaScript is executed on the client side that’s why it is very fast. Execute quickly because they do not
require a trip to the server.

Simplicity : Simple and easy to run. Syntax, rules and regulations mostly same as C , Java Programming
language.

Popularity: JavaScript is a very popular web language because it is used every where on the web.

Interoperability: JavaScript plays nicely with other languages and can be used in a wide range of applications.

Server Load : JavaScript reduce the server load as it executes on the client side. Although we can run java script
also on server with NodeJS.

Browser Compatible: JavaScript supports all modern browsers. It can execute on any browser and produce same
result.

Regular Updates: JavaScript updated annually by ECMA.

Rich interfaces: Gives the ability to create rich interfaces.


Disadvantages of JavaScript

Code Visibility: Code is always visible to everyone , anyone can view JavaScript code.

Security : Leading Security problem.

Browser Support. JavaScript is sometimes interpreted differently by different browsers. This


makes it somewhat difficult to write cross-browser code.

Stop Render: One error in JavaScript code can stop whole website to render.

Debugging Support : Not fruitful debugging support. Hence difficult for the developer to detect
the matter .

User can turn off it from browser.


Client side scripting Server side scripting
Source code is not visible to user because it’s output
Source code is visible to user.
of server side is a HTML page.

In this any server side technology can be use and it


It usually depends on browser and it’s version. does not
depend on client.

It runs on user’s computer. It runs on web server.

There are many advantages link with this like faster The primary advantage is it’s ability to highly
response times, a more interactive application. customize, access rights based on user.

It does not provide security for data. It provides more security for data.

It is a technique that uses scripts on web server to


It is a technique use in web development in which
produce a response that is customized for each
scripts runs on clients browser.
clients request.

HTML, CSS and javascript are used. PHP, Python, Java, Ruby are used.

End user can Turn off it from browser. End user can no turn off it from browser.
A Simple Script
<html>
<head><title>First JavaScript Page</title></head>
<body>
<h1>First JavaScript Page</h1>
<script type="text/javascript">
[Link]("<hr>");
[Link]("Hello World Wide Web");
[Link]("<hr>");
</script>
</body>
</html>
External JavaScript
<html>
<head><title>First JavaScript Program</title></head>
<body>
<script type="text/javascript"
src="your_source_file.js"></script>
</body>
</html> Inside your_source_file.js
[Link]("<hr>");
[Link]("Hello World Wide Web");
[Link]("<hr>");

• Use the src attribute to include JavaScript codes from an external file.
• The scripts inside an HTML document is interpreted in the order they appear in the document.
• Scripts in a function is interpreted when the function is called.
• So where you place the <script> tag matters.
Using innerHTML
To access an HTML element, JavaScript can use the

[Link](id) method.

The id attribute defines the HTML element.


<html>
<body>

<h1>My First Web Page</h1>

<p id="demo"></p>

<script>
[Link]("demo").innerHTML = ”Hello World”;
</script>

</body>
</html>
Hiding JavaScript from Incompatible Browsers

<script type="text/javascript">
[Link]("Hello, WWW");
</script>
<noscript>
Your browser does not support JavaScript.
</noscript>

The <noscript> tag defines an alternate content to be displayed to users, If disabled


scripts in their browser or browser that doesn't support script.
Identifier
• Same as Java/C++ 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 and Variable Declaration
<html> There are 3 ways to declare a JavaScript variable:
<body> •Using var
•Using let
•Using const
<h2>JavaScript Variables</h2>

<p>In this example, x, y, and z are variables.</p>

<p id="demo"></p> Attributes of Javascript variables :


It is a case sensitive. (mynum and MyNum are different variables)
<script> It cannot contain punctuation, space or start with a digit
var x = 5; It cannot be a JavaScript reserved word
var y = 6;
var z = x + y;
[Link]("demo").innerHTML ="value of z is: " + z;
</script>

</body>
</html>
Differences between var, let, and const

var let const

The scope of a var variable is The scope of a let variable is block The scope of a const variable is block
functional scope. scope. scope.

It can be updated and re-declared into It can be updated but cannot be It cannot be updated or re-declared
the scope. re-declared into the scope. into the scope.

It can be declared without It can be declared without It cannot be declared without


initialization. initialization. initialization.

It can be accessed without It cannot be accessed without


It cannot be accessed without
initialization as its default value is initialization, as it cannot be declared
initialization, as it returns an error.
“undefined”. without initialization.
Data Types
• Primitive data types
• Number: integer & floating-point numbers
• Boolean: true or false

• Composite data types (or Complex data types)


• Object: a named collection of data
• Array: a sequence of values (an array is actually a predefined object)
• String: a sequence of alphanumeric characters

• Special data types


• Null: the only value is "null" – to represent nothing.
• Undefined: the only value is "undefined" – to represent the value of an unintialized variable
Operators
• Arithmetic operators
• +, -, *, /, %

• Post/pre increment/decrement
++, --

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


• OP1 && OP2

• || – Logical OR
• OP1 || OP2

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

Bitwise operators
&, |, ^, >>, <<, >>>
Conditional Statements
•“if” statement
•“if … else” statement
•"? :" ternary conditional statement
•“switch” statement

• The syntax of these statements are similar to those found in C and


Java.
Looping Statement
• “for” Loops
• “for/in” Loops
• “while” Loops
• “do … while” Loops
• “break” statement
• “continue” statement

• All except "for/in" loop statements have the same syntax as those found
in C and Java.
“for/in” statement
for (var variable in object)
{
statements;
}

• To iterate through all the properties in "object".


• "variable" takes the name of each property in "object"
• Can be used to iterate all the elements in an Array object.
var cars = ["Saab", "Volvo", "BMW"];
txt="";
for(var a in cars)
{
txt= txt + cars[a];
}
[Link](txt);
Array
• An array is a special variable, which can hold more than one values.
• Array is an object that represents a collection elements.
• There are 2 ways to create array in JavaScript

(1)By Array literal :

var arrayname=[value1,value2.....valueN];

(2)By Array object (using new keyword)

var arrayname =new Array(value1,value2.....valueN]);

• Array Can store values of different types


❑ Consists of various methods to manipulate its elements.

e.g., reverse(), push(), unshift(), pop(),shift(), concat(), etc

[Link]
Array Examples
<script>
var Car = new Array(3);
Car[0] = "Ford"; Access Array
Car[1] = "Toyota";
Car[2] = "Honda"; Elements
var Car2 = new Array("Ford", "Toyota", "Honda");

var Car3 = ["odi", "innova", "vagon"];

[Link](Car2); // output : Ford,Toyota,Honda

[Link]("Yamaha");
[Link](Car2); // output : Ford,Toyota,Honda,Yamaha

[Link]();
[Link](Car2); // output : Ford,Toyota,Honda

var data = [Link](Car3);


[Link](data); // output : Ford,Toyota,Honda,odi,innova,vagon
</script>
// An array of 3 elements, each element is undefined
var tmp1 = new Array(3);

// An array of 3 elements with initial values


var tmp2 = new Array(10, 100, -3);

// An array of 3 elements with initial values


// of different types
var tmp3 = new Array(1, "a", true);

// Makes tmp3 an array of 10 elements


[Link] = 10; // tmp[3] to tmp[9] are undefined.

// Makes tmp3 an array of 100 elements


tmp3[99] = "Something";
// tmp[3] to tmp[98] are undefined.
Pop up Boxes
• Popup boxes can be used to raise an alert, or to get confirmation on any input or
to have a kind of input from the users.
• JavaScript supports three types of popup boxes.
• Alert box
• Confirm box
• Prompt box
Alert Box
• An alert box is 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.
• It can be used to display the result of validation.

Code
<html>
<head>
<title>Alert Box</title>
</head>
<body>
<script>
alert("Hello World");
</script>
</body>
</html>
Confirm Box
• A confirm box is used if you want the user to 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.
• Example :
Code
<script>
var a = confirm(“Are you sure??");
if(a==true) {
alert(“Record Deleted”);
}
else {
alert(“Record Not Deleted”);
}
</script>
Prompt Box
• A prompt box is used if you want the user to input a value.
• When a prompt box pops up, user have to click either "OK" or "Cancel" to proceed,
If the user clicks "OK" the box returns the input value, If the user clicks "Cancel"
the box returns null.
• Example:

Code
<script>
var a = prompt(“Enter Name");
alert(“User Entered ” + a);
</script>
Functions
• A JavaScript function is a block of code designed to perform a particular task.
• A JavaScript function is executed when "something" invokes it.
• A JavaScript function is defined with the function keyword, followed by a name,
followed by parentheses ().
• The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
• The code to be executed, by the function, is placed inside curly brackets.
• Example :
Code
function myFunction(p1, p2) {
return p1 * p2;
}
Functions (Cont.)
• When JavaScript reaches a return statement, the function will stop executing.
• If the function was invoked from a statement, JavaScript will "return" to execute
the code after the invoking statement.
• The code inside the function will execute when "something" invokes (calls) the
function:
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
Functions (Return Values)
// A function can return value of any type using the keyword "return".
// The same function can possibly return values of different types
function foo (p1)
{
if (typeof(p1) == "number")
return 0;// Return a number
else
if (typeof(p1) == "string")
return "zero"; // Return a string

// If no value being explicitly returned


// "undefined" is returned.
}

foo(1); // returns 0
foo("abc"); // returns "zero"
foo(); // returns undefined
Variable Arguments
// "arguments" is a local variable (an array) available in every function
// You can either access the arguments through parameters
or through the "arguments" array.

[Link](a);
function sum ()
{
var s = 0;
for(var i = 0; i < [Link]; i++)
s += arguments[i];
return s;
}

var a = sum(1, 2, 3); // returns 6


var a = sum(1, 2, 3, 4, 5);// returns 15
var a = sum(1, 2, "3", 4, 5); // returns ?
JavaScript - Arrow
Function
❑It allows you to create functions in a cleaner way compared to regular functions.

Arrow Function Syntax

let myFunction = (arg1, arg2, ...argN) => { statement(s) }

Here,
myFunction - is the name of the function
arg1, arg2, ...argN - are the function arguments
statement(s) - is the function body
Example 2: Arrow Function with Multiple Argument
Example 1: Arrow Function with No Argument
let sum = (a, b) => {
let result = a + b; let greet = () => {
return result; [Link]('Hello');
} }
let result1 = sum(5,7); greet(); // Hello
[Link](result1); // 12
Built-In Functions
• parseInt(s)
• eval(expr)

• evaluates an expression or statement • Converts string literals to integers


• eval("3 + 4"); • Parses up to any character that is not part of a valid integer
// Returns 7 (Number) • parseInt("3 chances") // returns 3
• eval("alert('Hello')"); • parseInt(" 5 alive") // returns 5
// Calls the function alert('Hello') • parseInt("How are you") // returns NaN

• isFinite(x) • parseFloat(s)

• Determines if a number is finite • Finds a floating-point value at the beginning of a string.


• parseFloat("3e-1 xyz") // returns 0.3
• parseFloat("13.5 abc") // returns 13.5
• isNaN(x)

• Determines whether a value is “Not a Number”


JavaScript Objects
• An object is just a special kind of data, with properties and methods.

• Accessing Object Properties

• Properties are the values associated with an object.


• The syntax for accessing the property of an object is below

[Link]

• This example uses the length property of the Javascript’s inbuilt object(String) to find the length of a string:
var message="Hello World!";
var x=[Link];

• Accessing Object Methods

• Methods are the actions that can be performed on objects.


• You can call a method with the following syntax.

[Link]()

• This example uses the toUpperCase method of the String object to convert string to upper case:
var message="Hello World!";
var x=[Link]();
JavaScript’s inbuilt Objects
• JavaScript comes with some inbuilt objects which are,
• String
• Date
• Array
• Boolean
• Math
• RegExp
etc….
Strings
• The JavaScript string is an object that represents a sequence of characters.
• A string in a JavaScript is wrapped with single or double quotes
• There are 2 ways to create string in JavaScript

(1)By string literal : The string literal is created using double quotes.
var stringname="string value";

(2)By string object (using new keyword)

var stringname=new String("string literal");

• Strings can be joined together with the + operator, which is called concatenation.
For Example,
mystring = “My name is ” + “Sandip”;
Access String Characters JavaScript Strings are immutable

You can access the characters in a string in two In JavaScript, strings are immutable.
ways. That means the characters of a string cannot
be changed.
•One way is to treat strings as an array.
For example,
For example,
var a = 'hello'; let a = 'hello';
[Link](a[1]); // "e“ a[0] = 'H';
[Link](a); // "hello"
•Another way is to use the method charAt().

For example,
var a = 'hello';
[Link]([Link](1)); // "e"
Methods Description String Object (Some useful methods)
charAt() It provides the char value present at the
specified index. slice() It is used to fetch the part of the given
concat() It provides a combination of two or more string. It allows us to assign positive as
strings. well negative index.
indexOf() It provides the position of a char value toLowerCase() It converts the given string into
present in the given string. lowercase letter.
lastIndexOf() It provides the position of a char value toLocaleLowerCase() It converts the given string into
present in the given string by searching a lowercase letter on the basis of host?s
character from the last position. current locale.
search() It searches a specified regular expression toUpperCase() It converts the given string into
in a given string and returns its position if uppercase letter.
a match occurs. toLocaleUpperCase() It converts the given string into
match() It searches a specified regular expression uppercase letter on the basis of host?s
in a given string and returns that regular current locale.
expression if a match occurs. toString() It provides a string representing the
replace() It replaces a given string with the specified particular object.
replacement. valueOf() It provides the primitive value of string
substr() It is used to fetch the part of the given object.
string on the basis of the specified starting split() It splits a string into substring array,
position and length. then returns that newly created array.
substring() It is used to fetch the part of the given trim() It trims the white space from the left
string on the basis of the specified index. and right side of the string.
Math Object in JavaScript
• The Math object allows you to perform mathematical tasks.
• The Math object includes several mathematical constants and methods.
• Math object has some properties which are,

Properties Description
E Returns Euler's number(approx.2.718)
LN2 Returns the natural logarithm of 2 (approx.0.693)
LN10 Returns the natural logarithm of 10 (approx.2.302)
LOG2E Returns the base‐2 logarithm of E (approx.1.442)
LOG10E Returns the base‐10 logarithm of E (approx.0.434)
PI Returns PI(approx.3.14)
SQRT1_2 Returns square root of ½
SQRT2 Returns square root of 2
Math Methods
Method Description Method Description
abs(x) Returns the absolute value of x exp(x) Returns the value of Ex
sin(x) Returns the sine of x (x is in radians) ceil(x) Returns x, rounded upwards to the nearest
cos(x) Returns the cosine of x (x is in radians) integer

tan(x) Returns the tan of x (x is in radians) floor(x) Returns x, rounded downwards to the
nearest integer
acos(x) Returns the arccosine of x, in radians
log(x) Returns the natural logarithm(base E) of x
asin(x) Returns the arcsine of x, in radians
round(x) Rounds x to the nearest integer
atan(x) Returns the arctangent of x as a numeric
value pow(x,y) Returns the value of x to the power of y

atan2(x) Returns arctangent of x max(x,y,z,...,n) Returns the number with the highest value

random() Returns random floating number between 0 sqrt(x) Returns the square root of x
to 1
Math Methods
<script>

[Link](Math.E); // Euler's number(approx.2.718)

var a = [Link](2,3);
[Link](a); // 8

var num = [Link]();


[Link](num); // 0.8124078072293648

var num2 = parseInt(1 + ([Link]() * 100));

[Link](num2); // Random Number betwween 1 to 100

[Link]([Link](2.7)); // 3
[Link]([Link](2.7)); // 2
[Link]([Link](2.7)); // 3

</script>
Date Object
❑The Date object works with dates and times.
❑Date objects are created with new Date().
There are different ways of instantiating (creating) a date:

new Date() new Date() creates a new date object with the current date and time:
;

Sat Jul 23 2022 [Link] GMT+0530 (India Standard


Time)

new Date(year, month, day, hour, minute, second, millisecond)

Sun Jul 31 2022 [Link] GMT+0530 (India Standard


Time)
Note: JavaScript counts months from 0 to 11:
User Defined Objects
• JavaScript allows you to create your own objects.
• A javascript object is an entity having properties and method.
• Once you create object you can bind Properties and Methods with it and further as per your
requirement you can retrieve that property values and invoke the methods.

There are two ways to create object:


(1) By Object Literal Notation
(2) By creating instance of Object (using New keyword)
Creating objects using new Object()
<script>
var person = new Object();

// Assign fields to object "person"

[Link] = “Sandip";
[Link] = “Patel";

// Assign a method to object "person"

[Link] = ()=>{
alert("Welcome " + [Link] + " " + [Link])
}

[Link](); // Call the method in "person"

</script>
Creating objects using Literal Notation
<script>
var person = {firstName: “Sandip", lastName: “Patel",
sayHi : function()
{
alert("Hi! " + [Link] + " " + [Link]);
}
}

[Link](); // Call the method in "person"

</script>
DOM - Introduction
• The Document Object Model is the standard way to accessing documents.
• DOM allows scripts to dynamically access and update the content, structure, and style of a
document.
• Using JavaScript, you can create, modify and remove elements in the page dynamically.
• When a web page is loaded, the browser will consider all the tags/elements of page as an
object and creates a Document Object Model of the page.
• The HTML DOM model is constructed as a tree of Objects.
• With the DOM, JavaScript can access and change all the elements of an HTML document.
• The nodes in a document make up the page’s DOM tree, which describes the relationships
among elements
• Nodes are related to each other through child-parent relationships
• A node may have multiple children, but only one parent
• The document node in a DOM tree is called the root node.

43
HTML element
head element
title element
body element
h1 element
p element

p element
ul element
li element
li element
li element

44
The HTML DOM Tree of
Objects
With the object model, JavaScript gets all the power it needs to
create dynamic HTML:

❑We can change all the HTML elements in the page


❑We can change all the HTML attributes in the page
❑We can change all the CSS styles in the page
❑We can remove existing HTML elements and attributes
❑We can add new HTML elements and attributes
❑We can react to all existing HTML events in the page
❑We can create new HTML events in the page
Document Object Properties
Property Description
anchors Returns a collection of all the anchors in the document
applets Returns a collection of all the applets in the document
body Returns the body element of the document
cookie Returns all name/value pairs of cookies in the document

domain Returns the domain name of the server that loaded the document
forms Returns a collection of all the forms in the document
images Returns a collection of all the images in the document
links Returns a collection of all the links in the document (CSSs)
referrer Returns the URL of the document that loaded the current document
title Sets or returns the title of the document
URL Returns the full URL of the document
Document Object Methods
Method Description
write() Writes HTML expressions or JavaScript code to a
document
writeln() Same as write(), but adds a newline character after
each statement
open() Opens an output stream to collect the output from
[Link]() or [Link]()
close() Closes the output stream previously opened with
[Link]()
getElementById() Accesses element with a specified id
getElementsByName() Accesses all elements with a specified name
getElementsByTagName() Accesses all elements with a specified tag name
setTimeout(), Set a time period for calling a function once; or
clearTimeout() cancel it.
getElementById()
• When we suppose to get the reference of the element from HTML in JavaScript using id
specified in the HTML we can use this method.
• Example :
HTML
<html>
<body>
<input type=“text” id=“myText”>
</body>
</html>

JavaScript
<script>
function myFunction()
{
var txt = [Link](“myText”);
alert([Link]);
}
</script>
getElementsByName()
• When we suppose to get the reference of the elements from HTML in JavaScript using name
specified in the HTML we can use this method.
• It will return the array of elements with the provided name.
• Example :
JavaScript
<script>
HTML function myFunction()
<html> {
<body> a=[Link](“myText”)[0];
<input type=“text” alert([Link]);
name=“myText”> }
</body> </script>
</html>
getElementsByTagName()
• When we suppose to get the reference of the elements from HTML in JavaScript using name of
the tag specified in the HTML we can use this method.
• It will return the array of elements with the provided tag name.
• Example :
JavaScript
<script>
HTML function myFunction() {
<html> a=[Link](“input”);
<body> alert(a[0].value);
<input type=“text” name=“uname”> alert(a[1].value);
<input type=“text” name=“pword”> }
</body> </script>
</html>
Forms using DOM
• We can access the elements of form in DOM quite easily using the name/id of the
form.
• Example : JS
function f()
{
var a = [Link][“myForm”];
HTML var u = [Link];
<html> var p = [Link];
<body> if(u==“admin” && p==“123”)
<form name=“myForm”> {
<input type=“text” name=“uname”> alert(“valid”);
<input type=“text” name=“pword”> }
<input type=“button” onClick=“f()”> else
</form> {
</body> alert(“Invalid”);
</html> }
}
Validation
• Validation is the process of checking data against a standard or requirement.
• Form validation normally used to occur at the server, after client entered
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.
• JavaScript provides a way to validate form's data on the client's computer before
sending it to the web server.
Validation (Cont.)
Form validation generally performs two functions.
1. Basic Validation
• Emptiness
• Confirm Password
• Length Validation etc……
2. Data Format Validation
Secondly, the data that is entered must be checked for correct form and value.
• Email Validation
• Mobile Number Validation
• Enrollment Number Validation etc….
Validation using RegExp
• A regular expression is an object that describes a pattern of characters.
• Regular expressions are used to perform on text.
• A regular expression can be a single character, or a more complicated pattern.
• The test() method is a RegExp expression [Link] searches a string for a pattern, and returns
true or false, depending on the result.

• example:
var pattern = "^[\\w]"; // will allow only words in the string
var regex = new RegExp(pattern);
If([Link](testString))
{
//Valid
}
else
{
//Invalid
}
RegExp (Cont.) (Metacharacters)
• To find word characters in the string we can use \w
• We can also use [a-zA-Z0-9_] for the same
• To find non-word characters in the string we can use \W
• to find digit characters in the string we can use \d
• We can also use [0-9] for the same
• To find non-digit characters in the string we can use \D
• We can use \n for new line and \t for tab
Email Validation Using RegExp
JavaScript
<script>
function checkMail()
{
var a = [Link]("myText").value;
var pattern ="^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$”;
var regex = new RegExp(pattern);
if([Link](a))
{
alert("Valid");
}
else
{
alert("Invalid");
}
}
</script>
if (name == "") {
Form Validation - [Link]("Please Enter Your Name");
return false;
Example
<script> }
function validate() { else if (email == "" || ![Link](email)) {
var form1 = [Link]("Please enter a valid e-mail address.");
[Link]("RegForm"); return false;
var name = [Link]; }
var email = [Link]; else if (password == "") {
var phone = [Link]; alert("Please enter your password");
var what = [Link]; return false;
var password = [Link]; }
var else if([Link] <6){
regEmail=/^\w+([\.-]?\w+)*@\w+([\.-] alert("Password should be atleast 6 character long");
?\w+)*(\.\w{2,3})+$/g; return false;
var regPhone=/^\d{10}$/; }
else if (phone == "" || ![Link](phone)) {
alert("Please enter valid phone number.");
return false;
}
else if ([Link] == -1) {
alert("Please enter your course.");
return false;
}
}
</script>
<tr>
<form name="RegForm" method="post" id="RegForm" onsubmit="return
<td>Mobile:</td>
validate()" > <td><input type="text" size="40"
<table> name="Telephone" /> <br></td>
<tr> </tr>
<td colspan="2"><h1 style="text-align: <tr>
center;">REGISTRATION FORM</h1></td> <td>Select Your Course : </td>
<td></td> <td><select type="text"name="Subject">
<option>[Link]</option>
</tr>
<option>[Link]</option>
<tr> <option>BCA</option>
<td>Name :</td> <option>MCA</option>
<td><input type="text" size="40" </select> <br></td>
name="Name" /> <br /></td> </tr> <br/> <br/>
</tr> <tr>
<tr> <td>Comments:</td>
<td>E-mail Address:</td> <td><textarea cols="40" name="Comment">
</textarea> <br></td>
<td><input type="text" size="40"
</tr>
name="EMail" /><br></td> <tr>
</tr> <td></td>
<tr> <td><input type="submit" value="Submit"
<td>Password:</td> name="Submit" /> &nbsp;<input type="reset"
<td><input type="text" size="40" value="Reset" name="Reset" /> <br></td>
name="Password" /><br></td> </tr>
</tr> </table>
</form>
Event Handling in Java Script

HTML Element Properties


Event Description
className Sets or returns the class attribute of an element
id Sets or returns the id of an element
innerHTML Sets or returns the HTML contents (+text) of an element
style Sets or returns the style attribute of an element
tabIndex Sets or returns the tab order of an element
title Sets or returns the title attribute of an element
value Sets or returns the value attribute of an element
Mouse Events
Event Attribute Description
click onclick The event occurs when the user clicks on an element

dblclick ondblclick The event occurs when the user double-clicks on an element

mousedown onmousedown The event occurs when a user presses a mouse button over an
element
mousemove onmousemove The event occurs when a user moves the mouse pointer over an
element
mouseover onmouseover The event occurs when a user mouse over an element

mouseout onmouseout The event occurs when a user moves the mouse pointer out of an
element
mouseup onmouseup The event occurs when a user releases a mouse button over an
element
Keyboard Events

Event Attribute Description


keydown onkeydown The event occurs when the user is pressing a key or
holding down a key
keypress onkeypress The event occurs when the user is pressing a key or
holding down a key
keyup onkeyup The event occurs when a keyboard key is released
Form Events
Event Attribute Description
blur onblur The event occurs when a form element loses focus
change onchange The event occurs when the content of a form element, the
selection, or the checked state have changed (for <input>,
<select>, and <textarea>)
focus onfocus The event occurs when an element gets focus (for <label>,
<input>, <select>, textarea>, and <button>)
reset onreset The event occurs when a form is reset
select onselect The event occurs when a user selects some text (for <input>
and <textarea>)
submit onsubmit The event occurs when a form is submitted
focus and change events

.html
<body>
Select Product : <select name="" id="product">
<option value="45000">AC</option>
<option value="22000">TV</option>
<option value="15000">Refrigerator</option>
<option value="70000">Laptop</option> </select>
<br><br>
Net Prize : <input type="text" id="prize"> <br><br>
Quantity : <input type="text" id="quantity">
<br><br>
Total Amount :<input type="text" id="amount">
</body>

Find the script in next


slide
focus and change events
<script>
var product = [Link]("product");
var qunatity = [Link]("quantity");
var amount = [Link]("amount");
var prize = [Link]("prize");

[Link]("change",()=>{
[Link] = [Link];
});

[Link]("focus",()=>{
[Link]=[Link] * [Link];
});
</script>
mouseover and mouseout events
<body>
<img src="img/[Link]" alt="" id="bulb">
</body> [Link]

<script>
var a = [Link]("bulb");
[Link]("mouseover",()=>{
[Link]= "img/[Link]";
});

[Link]("mouseout",()=>{
[Link]
[Link]= "img/[Link]";
});
</script>
Keypress events
<body>
<p>Press any key to display Current Date :</p>
<input type="text" id="key">

<script>
var key = [Link]("key");
[Link]("keypress",()=>{
var a = new Date();
alert(a)
});
</script>
</body>
<body>
<input type="text" id="rows" placeholder="Enter Rows"> <br>
<input type="text" id="cols" placeholder="Enter Cols"> <br>
<input type="button" value="Generate Table" id="btn1">
</body>
<script>
var rows = [Link]("rows");
var cols = [Link]("cols");
var btn1 = [Link]("btn1");
[Link]("click",()=>{
[Link]("<table border='2' width='50%'>");
for(let i=0; i<[Link]; i++)
{
[Link]("<tr>")
for(j=0; j<[Link]; j++)
{
[Link]("<td>" + "[" +i+"]" + "["+j+"]" + "</td>");
}
[Link]("</tr>");
}
[Link]("</table>");
}); Click event
</script>
setTimeout() method setInterval() Method
❑The setInterval() method repeats a given function at
❑The setTimeout() method executes a function, after
every given time-interval.
waiting a specified number of milliseconds.
Syntax:
Syntax:
setInterval(function, milliseconds);
setTimeout(function, milliseconds);
Example : callme function will call after every 2 seconds.
Example : callme function will call after 2 seconds So here welcome in ASOIT will be continuously display
at
<script>
2 seconds time interval
setTimeout(callme,2000); <script>
function callme() { setInterval(callme,2000);
alert('Welcome in ASOIT'); function callme() {
} alert('Welcome in ASOIT');
</script> }
</script>
clearTimeout() method clearnterval() Method
❑The clearInterval() method clears a timer set with
❑The clearTimeout() function in javascript clears the
the setInterval() method.
timeout which has been set by setTimeout()function
❑To clear an interval, use the id returned from
❑To clear Timeout, use the id returned from
setInterval():
setTimeout()
Example :
Example :
t = setInterval(callme, 3000);
t = setTimeout(callme, 3000);
clearInterval(t);
clearTimeout(t);
setInterval function – Example
Change the background color of page at specific time interval. Background color will be changed after every
seconds
<body id="mybody">

</body>
<script>
var colors = ["red","green","blue","pink","black","orange"];
var mybody = [Link]("mybody");
var i=0;
setInterval(()=>{
[Link] = colors[i];
++i;
if(i==[Link])
{
i=0;
}
},1000)
</script>
Callbacks in Javascript (Function as arguments)
❑In JavaScript, you can also pass a function as an argument to a function.
❑This function that is passed as an argument inside of another function is called a callback function.
❑A callback is a function which is called when a task is completed, thus helps in preventing any kind of blocking and a
callback function allows other code to run in the meantime.
❑Generally Callback function is used in Asynchronous communication
❑In the above program, there are two functions.
function greet(name, callback) {
❑While calling the greet() function, two arguments (a
[Link]('Hi' + ' ' + name);
string value and a function) are passed.
callback();
❑The callMe() function is a callback function.
}

function callMe() {
[Link]('I am callback function'); ❑If you create a function to load an external resource
} (like a script or a file), you cannot use the content
before it is fully loaded. This is the perfect time to
greet('Peter', callMe); use a callback.
❑Ex: Function reading a file

Output :
Callbacks Function Example : Asynchronous communication
<script>
// program that shows the delay in execution
function greet() {
[Link]('Hello world');
}
function sayName(name) {
[Link]('Hello' + ' ' + name);
}

setTimeout(greet, 2000); // calling the function


sayName('ASOIT');
</script>

❑As you know, the setTimeout() method executes a block of code after the specified time.
❑Here, the greet() function is called after 2000 milliseconds (2 seconds).
❑During this wait, the sayName(‘ASOIT'); is executed. That is why Hello ASOIT is printed before Hello world.
❑The above code is executed asnchronously (the second function; sayName() does not wait for the first
function; greet() to complete).
JSON
❑JSON stands for JavaScript Object Notation.
❑It has been extended from the JavaScript scripting language.
❑The filename extension is .json.
❑JSON Internet Media type is application/json.
❑The JSON format is syntactically similar to the code for creating JavaScript ❑JavaScript has a built in function
objects. for converting JSON strings into
JavaScript objects:
❑Because of this, a JavaScript program can easily convert JSON data into
JavaScript objects. [Link]()
❑Since the format is text only, JSON data can easily be sent between
computers, and used by any programming language. JavaScript also has a built in
function for converting an object
❑You can receive pure text from a server and use it as a JavaScript object. into a JSON string:
❑You can send a JavaScript object to a server in pure text format.
❑You can work with data as JavaScript objects, with no complicated parsing [Link]()
and translations.
Uses of JSON

❑It is used while writing JavaScript based applications that includes browser
extensions and websites.
❑JSON format is used for transmitting structured data over network connection.
❑It is primarily used to transmit data between a server and web applications.
❑Web services and APIs use JSON format to provide public data.
❑It can be used with modern programming languages.
❑It is a lightweight text-based interchange format.
❑JSON is language independent.
JSON Syntax Rules

❑JSON syntax is derived from JavaScript object notation syntax


❑Data is in name/value pairs
❑Data is separated by commas
❑Curly braces hold objects
❑Square brackets hold arrays
JSON Array &
Object
<body>
<h2>Access Array Values</h2>
<p id="demo"></p>

<script>
var myJSON = '{"name":"John", "age":30, "cars":["Ford", "BMW", "Fiat"]}';
var myObj = [Link](myJSON);
[Link]("demo").innerHTML = [Link][0];
</script>
</body>

You might also like