0% found this document useful (0 votes)
18 views

Java Script: Variables &scope, Data Types, Control Structures, Array Methods

css

Uploaded by

rahulnakka74
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)
18 views

Java Script: Variables &scope, Data Types, Control Structures, Array Methods

css

Uploaded by

rahulnakka74
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
You are on page 1/ 35

GMR Institute of Technology

GMRIT/ADM/F-44
Rajam, Andhra Pradesh
REV.: 00
(An Autonomous Institution Affiliated to JNTUGV, AP)

Cohesive Teaching – Learning Practices (CTLP)


Class 4th Sem. – B. Tech Department: CSE
Course
Course Web Coding and Development 21CS405
Code
Prepared by Mr. Gangu Dharmaraju
Java Script: Variables &Scope, Data types, Control Structures, Array Methods,
Lecture Topic Functions, Events, Validations, Objects, Document Object Model (DOM),
Browser Object Model (BOM)
Course Outcome (s) CO2, CO3 Program Outcome (s) PO1, PO2 , PSO2
Duration 1 Hr Lecture 1 to 6 Unit II
Pre-requisite (s) Knowledge of Basic Programming

❖ Objective

❖ Apply dynamic effects and validations using JavaScript skills to real-world projects
❖ Demonstrating the ability to build interactive and dynamic web applications

❖ Intended Learning Outcomes (ILOs)

At the end of this session the students will able to:

A. Understand the basic syntax and structure of JavaScript program


B. Define and call functions with parameters and return values
C. Create and manipulate arrays using array methods (e.g., push, pop, splice).
D. Access and modify HTML elements using the Document Object Model (DOM).

❖ 2D Mapping of ILOs with Knowledge Dimension and Cognitive Learning Levels of


RBT

Cognitive Learning Levels


Knowledge
Remember Understand Apply Analyse Evaluate Create
Dimension
Factual
Conceptual B A C
Procedural D
Meta Cognitive

GMRIT, Rajam, Andhra Pradesh


❖ Teaching Methodology

❖ Chalk & Board, Visual Presentation

❖ Evocation

❖ Deliverables
Lecture -1:
➢ JAVASCRIPT
❖ JavaScript is the scripting language of the Web.
❖ JavaScript is used in millions of Web pages to add functionality, validate forms,
detect browsers, and much more.
➢ Introduction to JavaScript
❖ JavaScript is used in millions of Web pages to improve the design, validate forms,
detect browsers, create cookies, and much more.
❖ JavaScript is the most popular scripting language on the Internet, and works in all
major browsers, such as Internet Explorer, Mozilla Firefox, and Opera.
➢ What is JavaScript?
❖ JavaScript was designed to add interactivity to HTML pages
❖ JavaScript is a scripting language
❖ A scripting language is a lightweight programming language
❖ JavaScript is usually embedded directly into HTML pages
❖ JavaScript is an interpreted language (means that scripts execute without
preliminary compilation)
❖ Everyone can use JavaScript without purchasing a license
Java and JavaScript are two completely different languages in both concept and
design!
Java (developed by Sun Microsystems) is a powerful and much more complex
programming language - in the same category as C and C++.

GMRIT, Rajam, Andhra Pradesh


➢ What can a JavaScript Do ?
❖ JavaScript gives HTML designers a programming tool - HTML authors are normally
not programmers, but JavaScript is a scripting language with a very simple syntax!
Almost anyone can put small "snippets" of code into their HTML pages
❖ JavaScript can put dynamic text into an HTML page - A JavaScript statement like
this: document.write("<h1>" + name + "</h1>") can write a variable text into an
HTML page
❖ JavaScript can react to events - A JavaScript can be set to execute when something
happens, like when a page has finished loading or when a user clicks on an HTML
element
❖ JavaScript can read and write HTML elements - A JavaScript can read and change
the content of an HTML element
❖ JavaScript can be used to validate data - A JavaScript can be used to validate form
data before it is submitted to a server. This saves the server from extra processing
❖ JavaScript can be used to detect the visitor's browser - A JavaScript can be used to
detect the visitor's browser, and - depending on the browser - load another page
specifically designed for that browser
❖ JavaScript can be used to create cookies - A JavaScript can be used to store and
retrieve information on the visitor's computer.
➢ JavaScript Variables
❖ Variables are "containers" for storing information.
❖ JavaScript variables are used to hold values or expressions.
❖ A variable can have a short name, like x, or a more descriptive name, like carname.
❖ Rules for JavaScript variable names:
o Variable names are case sensitive (y and Y are two different variables)
o Variable names must begin with a letter or the underscore character
Note: Because JavaScript is case-sensitive, variable names are case-sensitive.
❖ Example
o A variable's value can change during the execution of a script. You can refer to a
variable by its name to display or change its value.
<html>
<body>
<script type="text/javascript">
var firstname;
firstname="Welcome";
document.write(firstname);
document.write("<br />");
firstname="XYZ";
document.write(firstname);
</script>
<p>The script above declares a variable,
assigns a value to it, displays the value, change the value,
and displays the value again.</p>
</body>
</html>
Output :
Welcome
XYZ

GMRIT, Rajam, Andhra Pradesh


o The script above declares a variable, assigns a value to it, displays the value,
change the value, and displays the value again.
❖ Declaring (Creating) JavaScript Variables
o Creating variables in JavaScript is most often referred to as "declaring"
variables.
o You can declare JavaScript variables with the var statement:
var x;
var carname;
o After the declaration shown above, the variables are empty (they have no
values yet).
o However, you can also assign values to the variables when you declare
them:
var x=5;
var carname="Scorpio";
o After the execution of the statements above, the variable x will hold the
value 5, and carname will hold the value Scorpio.
o Note: When you assign a text value to a variable, use quotes around the
value.
❖ Assigning Values to Undeclared JavaScript Variables
o If you assign values to variables that have not yet been declared, the
variables will automatically be declared.
o These statements:
x=5;
carname="Scorpio";
have the same effect as:
var x=5;
var carname="Scorpio";
❖ Redeclaring JavaScript Variables
o If you redeclare a JavaScript variable, it will not lose its original value.
var x=5;
var x;
o After the execution of the statements above, the variable x will still have the
value of 5. The value of x is not reset (or cleared) when you redeclare it.
➢ Scope
❖ Scope determines the accessibility (visibility) of variables.
❖ JavaScript variables have 3 types of scope:
I. Block scope
II. Function scope
III. Global scope
i. Block Scope
o Before ES6 (2015), JavaScript variables had only Global Scope and Function
Scope.
o ES6 introduced two important new JavaScript keywords: let and const.
o These two keywords provide Block Scope in JavaScript.
o Variables declared inside a { } block cannot be accessed from outside the
block:
o Example
{
let x = 2;

GMRIT, Rajam, Andhra Pradesh


}
// x can NOT be used here
o Variables declared with the var keyword can NOT have block scope.
o Variables declared inside a { } block can be accessed from outside the block.
o Example
{
var x = 2;
}
// x CAN be used here
ii. Local Scope/Function Scope
o Variables declared within a JavaScript function, are LOCAL to the function:
o Example
// code here can NOT use x

function myFunction() {
let x = 1216;
// code here CAN use x
}
// code here can NOT use x
o Local variables have Function Scope:
o They can only be accessed from within the function.
iii.Global Scope
o A variable declared outside a function, becomes GLOBAL.
o Example
let x = 1216;
// code here can use x
function myFunction() {
// code here can also use x
}
o Global variables can be accessed from anywhere in a JavaScript program.
o Variables declared with var, let and const are quite similar when declared
outside a block.
➢ DataTypes
❖ Numbers - are values that can be processed and calculated. You don't enclose them
in quotation marks. The numbers can be either positive or negative.
❖ Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript
uses the string literally; it doesn't process it. You'll use strings for text you want
displayed or values you want passed along.
❖ Boolean (true/false) - lets you evaluate whether a condition meets or does not
meet specified criteria.
❖ Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number,
whereas null is the absence of any value.l

GMRIT, Rajam, Andhra Pradesh


Lecture -2
➢ JavaScript Operators
❖ Javascript operators are used to perform different types of mathematical and logical
computations.
i. Arithmetic Operators
o Arithmetic operators are used to perform arithmetic between variables
and/or values.
o Given that y=5, the table below explains the arithmetic operators:

o The + Operator Used on Strings


The + operator can also be used to add string variables or text values
together.
To add two or more string variables together, use the + operator.
Example:-
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
After the execution of the statements above, the variable txt3 contains "What
a verynice day".
If you add a number and a string, the result will be a string.
ii. Assignment Operators
o Assignment operators are used to assign values to JavaScript variables.
o Given that x=10 and y=5, the table below explains the assignment operators:

GMRIT, Rajam, Andhra Pradesh


iii. Comparison Operators
o Comparison operators are used in logical statements to determine equality or
difference between variables or values.
o Given that x=5, the table below explains the comparison operators:

iv. Logical Operators


o Logical operators are used to determine the logic between variables or
values.
o Given that x=6 and y=3, the table below explains the logical operators:

v. Conditional Operator
o JavaScript also contains a conditional operator that assigns a value to a
variable based on some condition.
o Syntax
variablename=(condition)?value1:value2
o Example:
greeting=(visitor=="PRES")?"Dear President ":"Dear ";
- If the variable visitor has the value of "PRES", then the variable greeting
will be assigned the value "Dear President " else it will be assigned
"Dear".
vi. Bitwise Operators
o Bit operators work on 32 bits numbers.
o Any numeric operand in the operation is converted into a 32 bit number.
The result is converted back to a JavaScript number.
Operator Description Example Same as Result Decimal
& AND 5&1 0101 & 0001 0001 1
| OR 5|1 0101 | 0001 0101 5
~ NOT ~5 ~0101 1010 10

GMRIT, Rajam, Andhra Pradesh


^ XOR 5^1 0101 ^ 0001 0100 4
<< left shift 5 << 1 0101 << 1 1010 10
>> right shift 5 >> 1 0101 >> 1 0010 2
>>> unsigned 5 >>> 1 0101 >>> 1 0010 2
right shift

➢ Conditional Statements
❖ Very often when you write code, you want to perform different actions for
different decisions. You can use conditional statements in your code to do this.
❖ In JavaScript we have the following conditional statements:
o if statement - use this statement if you want to execute some code only if a
specified condition is true
o if...else statement - use this statement if you want to execute some code if the
condition is true and another code if the condition is false
o if...else if....else statement - use this statement if you want to select one of many
blocks of code to be executed
o switch statement - use this statement if you want to select one of many blocks
of code to be executed
 if Statement
o You should use the if statement if you want to execute some code only if a
specified condition is true.
o Syntax
if (condition)
{
code to be executed if condition is true
}
o Example
<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date();
var time=d.getHours();
if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>
 If...else Statement
o If you want to execute some code if a condition is true and another code if the
condition is not true, use the if....else statement.
o Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

GMRIT, Rajam, Andhra Pradesh


o Example
<script type="text/javascript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date();
var time = d.getHours();

if (time < 10)


{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}
</script>

 If...else if...else Statement


o You should use the if....else if...else statement if you want to select one of many
sets of lines to execute.
o Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and
condition2 are not true
}
o Example
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
Else
{

GMRIT, Rajam, Andhra Pradesh


document.write("<b>Hello World!</b>");
}
</script>

 Switch Statement
o You should use the switch statement if you want to select one of many blocks of
code to be executed.
o Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is
different from case 1 and 2
}
o This is how it works: First we have a single expression n (most often a variable),
that is evaluated once. The value of the expression is then compared with the
values for each case in the structure. If there is a match, the block of code
associated with that case is executed. Use break to prevent the code from
running into the next case automatically.
o Example
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>

GMRIT, Rajam, Andhra Pradesh


➢ Controlling(Looping) Statements
❖ Loops in JavaScript are used to execute the same block of code a specified number of
times or while a specified condition is true.
❖ Very often when you write code, you want the same block of code to run over and
over again in a row. Instead of adding several almost equal lines in a script we can
use loops to perform a task like this.
❖ In JavaScript there are two different kind of loops:
o for - loops through a block of code a specified number of times
o while - loops through a block of code while a specified condition is true
 The for Loop
o The for loop is used when you know in advance how many times the script
should run.

o Syntax
for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}
o Example
Explanation: The example below defines a loop that starts with i=0. The loop
will continue to run as long as i is less than, or equal to 10. i will increase by 1
each time the loop runs.
Note: The increment parameter could also be negative, and the <= could be any
comparing statement.
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
Result:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

GMRIT, Rajam, Andhra Pradesh


 While Loop
o Loops in JavaScript are used to execute the same block of code a specified
number of times or while a specified condition is true.
o The while loop is used when you want the loop to execute and continue
executing while the specified condition is true.
o Syntax:
while (var<=endvalue)
{
code to be executed
}
Note: The <= could be any comparing statement.
o Example
Explanation: The example below defines a loop that starts with i=0. The loop will
continue to run as long as i is less than, or equal to 10. i will increase by 1 each time
the loop runs.
<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=10)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>
</body>
</html>
Result:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
 do...while Loop
o The do...while loop is a variant of the while loop. This loop will always execute a
block of code ONCE, and then it will repeat the loop as long as the specified
condition is true. This loop will always be executed at least once, even if the
condition is false, because the code is executed before the condition is tested.
o Syntax
do
{
code to be executed

GMRIT, Rajam, Andhra Pradesh


}
while (var<=endvalue);
o Example
<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
while (i<0);
</script>
</body>
</html>
Result
The number is 0

➢ Break and Continue


❖ There are two special statements that can be used inside loops: break and
continue.
❖ There are two special statements that can be used inside loops: break and
continue.
 break
o The break command will break the loop and continue executing the code that
follows after the loop (if any).
o Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
Result
The number is 0
The number is 1
The number is 2

GMRIT, Rajam, Andhra Pradesh


 continue
o The continue command will break the current loop and continue with the next
value.
o Example
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
Result
The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

Lecture-3
➢ Arrays
❖ An array object is used to create a database-like structure within a script. Grouping
data points (array elements) together makes it easier to access and use the data in
a script. There are methods of accessing actual databases (which are beyond the
scope of this series) but here we're talking about small amounts of data.
❖ An array can be viewed like a column of data in a spreadsheet. The name of the
array would be the same as the name of the column. Each piece of data (element) in
the array is referred to by a number (index), just like a row number in a column.
❖ An array is an object. Earlier, I said that an object is a thing, a collection of
properties (array elements, in this case) grouped together.

GMRIT, Rajam, Andhra Pradesh


❖ Elements can be of any type: character string, integer, Boolean, or even another
array. An array can even have different types of elements within the same array.
Each element in thearray is accessed by placing its index number in brackets, i.e.
myCar[4]. This would mean that we are looking for data located in the array myCar
which has an index of "4." Since the numbering of an index starts at "0," this would
actually be the fifth index. For instance, in the following array,
var myCar = new Array("Chev","Ford","Buick","Lincoln","Truck");
alert(myCar[4])
the data point with an index of "4" would be Truck. In this example, the indexes are
numbered as follows: 0=Chev, 1=Ford, 2=Buick, 3=Lincoln, and 4=Truck. When
creating loops, it's much easier to refer to a number than to the actual data itself.
❖ The Size of the Array
o The size of an array is determined by either the actual number of elements it
contains or by actually specifying a given size. You don't need to specify the size
of the array. Sometimes, though, you may want to pre-set the size, e.g.:
var myCar = new Array(20);
o That would pre-size the array with 20 elements. You might pre-size the array in
order to set aside the space in memory.

❖ ArrayMethods:
- concat(): Joins two or more arrays, and returns a copy of the joined arrays
- copyWithin(): Copies array elements within the array, to and from specified
positions
- entries(): Returns a key/value pair Array Iteration Object
- every(): Checks if every element in an array pass a test
- fill(): Fill the elements in an array with a static value
- filter(): Creates a new array with every element in an array that pass a test
- find(): Returns the value of the first element in an array that pass a test
- findIndex(): Returns the index of the first element in an array that pass a test
- forEach(): Calls a function for each array element
- from(): Creates an array from an object
- includes(): Check if an array contains the specified element
- indexOf(): Search the array for an element and returns its position
- isArray(): Checks whether an object is an array
- join(): Joins all elements of an array into a string
- keys(): Returns a Array Iteration Object, containing the keys of the original array
- lastIndexOf(): Search the array for an element, starting at the end, and returns its
position
- map(): Creates a new array with the result of calling a function for each array
element
- pop(): Removes the last element of an array, and returns that element

GMRIT, Rajam, Andhra Pradesh


- push(): Adds new elements to the end of an array, and returns the new length
- reduce(): Reduce the values of an array to a single value (going left-to-right)
- reduceRight(): Reduce the values of an array to a single value (going right-to-left)
- reverse(): Reverses the order of the elements in an array
- shift(): Removes the first element of an array, and returns that element
- slice(): Selects a part of an array, and returns the new array
- some(): Checks if any of the elements in an array pass a test
- sort(): Sorts the elements of an array
- splice(): Adds/Removes elements from an array
- toString(): Converts an array to a string, and returns the result
- unshift(): Adds new elements to the beginning of an array, and returns the new
length
- valueOf(): Returns the primitive value of an array:

Note: Try with some examples by own

➢ Functions
❖ A function (also known as a method) is a self-contained piece of code that performs
a particular "function". You can recognise a function by its format - it's a piece of
descriptive text, followed by open and close brackets.A function is a reusable code-
block that will be executed by an event, or when the function is called.
❖ To keep the browser from executing a script when the page loads, you can put your
script into a function.
❖ A function contains code that will be executed by an event or by a call to that
function.
❖ You may call a function from anywhere within the page (or even from other pages if
the function is embedded in an external .js file).
❖ Functions can be defined both in the <head> and in the <body> section of a
document. However, to assure that the function is read/loaded by the browser
before it is called, it could be wise to put it in the <head> section.
❖ Example
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessage()" >
</form>
</body>
</html>

GMRIT, Rajam, Andhra Pradesh


o If the line: alert("Hello world!!") in the example above had not been put within a
function, it would have been executed as soon as the line was loaded. Now, the
script is not executed before the user hits the button. We have added an onClick
event to the button that will execute the function displaymessage() when the
button is clicked.
o You will learn more about JavaScript events in the JS Events chapter.
❖ How to Define a Function
o The syntax for creating a function is:
function functionname(var1,var2,...,varX)
{
some code
}
var1, var2, etc are variables or values passed into the function. The { and the }
defines the start and end of the function.
Note: A function with no parameters must include the parentheses () after the
function name:
function functionname()
{
some code
}
Note: Do not forget about the importance of capitals in JavaScript! The word
function must be written in lowercase letters, otherwise a JavaScript error occurs!
Also note that you must call a function with the exact same capitals as in the
function name.
❖ The return Statement
o The return statement is used to specify the value that is returned from the
function. So, functions that are going to return a value must use the return
statement.
o Example
The function below should return the product of two numbers (a and b):
function prod(a,b)
{
x=a*b;
return x;
}
When you call the function above, you must pass along two parameters:
product=prod(2,3);

o The returned value from the prod() function is 6, and it will be stored in the
variable called product.
❖ The Lifetime of JavaScript Variables
o When you declare a variable within a function, the variable can only be accessed
within that function. When you exit the function, the variable is destroyed.
These variables are called local variables. You can have local variables with the
same name in different functions, because each is recognized only by the
function in which it is declared.
o If you declare a variable outside a function, all the functions on your page can
access it. The lifetime of these variables starts when they are declared, and ends
when the page is closed.

GMRIT, Rajam, Andhra Pradesh


❖ Function Expression
o Example
let displayNumbers=function(startValue,endValue,incVal){
let result='';
for(let i=startValue;i<=endValue;i+=incVal)
result+=`${i} `;
console.log(result);
}
displayNumbers(100,200,10);
Lecture - 4
➢ Validations
❖ Validation is the process of checking whether the information provided by the
front-end user is correct or not as per the requirements. If the data provided by the
client was incorrect or missing, then the server will have to send that data back to
the client and request for resubmitting the form with the correct information.

❖ Generally, the validation process is done at the server-side, which sends that
validation information to the front-end user. This process wastes the execution
time and user time.
❖ JavaScript gives us a way to validate the form's data before sending it to the server-
side. Validation in forms generally performs two functions, which are as follows:
i. Basic validation- It is a process to make sure that all of the mandatory fields
are filled or not.
ii. Data Format validation- As its name implies, it is the process to check that
entered data is correct or not. We have to include appropriate logic for
testing the correctness of data.
❖ Basic Form Validation
o It validates the mandatory input fields of the form, whether the required fields
are filled or not.
o Let us understand the process of basic form validation by using the following
example.
<!DOCTYPE html>
<html>

<head>
<title>Example of Basic form Validation</title>
<script>
function validateBasic() {
var name1 = document.basic.name.value;
var qual1 = document.basic.qual.value;
var phone1 = document.basic.phone.value;

if (name1 == "") {
alert("Name required");
return false;
}

if (qual1 == "") {
alert("Qualification required");

GMRIT, Rajam, Andhra Pradesh


return false;
}

if (phone1 == "") {
alert("Mobile number is required");
return false;
}

}
</script>
</head>

<body>
<center>
<h1>Basic Form Validation</h1>
<form name="basic" action="#" onsubmit="return
validateBasic()">
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td>Name: </td>
<td><input type="text" name="name"></td>
<tr>
<tr>
<td> Qualification: </td>
<td><input type="text" name="qual"></td>
</tr>
<tr>
<td>Phone no.:</td>
<td><input type="text" name="phone"></td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
<p id="d1"></p>
</center>
</body>
</html>

❖ Data Format Validation


o In data format validation, there is the checking of the entered data for the
correct value. It validates already filled input fields that whether the filled
information is correct or not.
o Let's understand the concept of data format validation with the following
example.
<!DOCTYPE html>
<html>
<head>
<title>Example of Basic form Validation</title>
<script>

GMRIT, Rajam, Andhra Pradesh


function validateBasic() {
var name1 = document.basic.name.value;
var qual1 = document.basic.qual.value;
var phone1 = document.basic.phone.value;
var id = document.basic.em.value;
if (name1 == "") {
alert("Name required");
return false;
}
if(name1.length<5){
alert("Username should be atleast 5 characters");
return false;
}
at = id.indexOf("@");
dot = id.lastIndexOf(".");
if (at < 1 || ( dot - at < 2 )) {
alert("Incorrect Email-ID")
return false;
}
if (qual1 == "") {
alert("Qualification required");
return false;
}
if (phone1 == "") {
alert("Mobile number is required");
return false;
}
if(phone1.length<10 || phone1.length>10){
alert("Mobile number should be of 10 digits");
return false;
}
}
</script>
</head>
<body>
<center>
<h1>Basic Form Validation</h1>
<form name="basic" action="#" onsubmit="return
validateBasic()">
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td>Name: </td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Email: </td>
<td><input type="email" name="em"></td>
</tr>
<tr>

GMRIT, Rajam, Andhra Pradesh


<td> Qualification: </td>
<td><input type="text" name="qual"></td>
</tr>
<tr>
<td>Phone no.:</td>
<td><input type="number" name="phone"></td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
<p id="d1"></p>
</center>
</body>
</html>
Lecture - 5
➢ What is an Event?
❖ Event Handlers
o Event Handlers are JavaScript methods, i.e. functions of objects, that allow us as
JavaScript programmers to control what happens when events occur.
o Directly or indirectly, an Event is always the result of something a user does. For
example, we've already seen Event Handlers like onClick and onMouseOver
that respond to mouse actions. Another type of Event, an internal change-of-
state to the page (completion of loading or leaving the page). An onLoad Event
can be considered an indirect result of a user action.
o Although we often refer to Events and Event Handlers interchangeably, it's
important to keep in mind the distinction between them. An Event is merely
something that happens - something that it is initiated by an Event Handler
(onClick, onMouseOver, etc...).
o The elements on a page which can trigger events are known as "targets" or
"target elements," and we can easily understand how a button which triggers a
Click event is a target element for this event. Typically, events are defined
through the use of Event Handlers, which are bits of script that tell the browser
what to do when a particular event occurs at a particular target. These Event
Handlers are commonly written as attributes of the target element's HTML tag.
o The Event Handler for a Click event at a form field button element is quite
simple to understand:
<INPUT TYPE="button" NAME="click1" VALUE="Click me for fun!"
onClick="event_handler_code">
o The event_handler_code portion of this example is any valid JavaScript and it
will be executed when the specified event is triggered at this target element.
o There are "three different ways" that Event Handlers can be used to trigger
Events or Functions.
 Method 1 (Link Events):
- Places an Event Handler as an attribute within an <A HREF= > tag, like this:
<A HREF="foo.html" onMouseOver="doSomething()"> ... </A>
- You can use an Event Handler located within an <A HREF= > tag to make
either an image or a text link respond to a mouseover Event. Just enclose the
image or text string between the <A HREF= > and the </A> tags.

GMRIT, Rajam, Andhra Pradesh


- Whenever a user clicks on a link, or moves her cursor over one, JavaScript is
sent a Link Event. One Link Event is called onClick, and it gets sent whenever
someone clicks on a link. Another link event is called onMouseOver. This one
gets sent when someone moves the cursor over the link.
- You can use these events to affect what the user sees on a page. Here's an
example of how to use link events . Try it out, View Source, and we'll go over
it.
<A HREF="javascript:void('')"
onClick="open('index.htm', 'links', 'height=200,width=200');">How to
Use Link Events
</A>
- The first interesting thing is that there are no <SCRIPT> tags. That's
because anything that appears in the quotes of an onClick or an
onMouseOver is automatically interpreted as JavaScript. In fact, because
semicolons mark the end of statements allowing you to write entire
JavaScripts in one line, you can fit an entire JavaScript program between the
quotes of an onClick. It'd be ugly, but you could do it.
- Here are the three lines of interest:
1. <A HREF="#" onClick="alert('Ooo, do it again!');">Click on me!
</A>
2. <A HREF="javascript:void('')" onClick="alert('Ooo, do it again!');">
Click on me!
</A>
3. <A HREF="javascript:alert('Ooo, do it again!')" >Click on me!
</A>
- In the first example we have a normal <A> tag, but it has the magic
onClick="" element, which says, "When someone clicks on this link, run
the little bit of JavaScript between my quotes." Notice, there's even a
terminating semicolon at the end of the alert. Question: is this required?
NO.
- Let's go over each line:
1. HREF="#" tells the browser to look for the anchor #, but there is no
anchor "#", so the browser reloads the page and goes to top of the page
since it couldn't find the anchor.
2. <A HREF="javascript:void('')" tells the browser not to go anywhere -
it "deadens" the link when you click on it. HREF="javascript: is the way to
call a function when a link (hyperlink or an HREFed image) is clicked.
3. HREF="javascript:alert('Ooo, do it again!')" here we kill two birds
with one stone. The default behavior of a hyperlink is to click on it. By
clicking on the link we call the window Method alert() and also at the
same time "deaden" the link.
The next line is
<A HREF="javascript:void('')" onMouseOver="alert('Hee hee!');">
Mouse over me!
</A>
- This is just like the first line, but it uses an onMouseOver instead of an
onClick.

GMRIT, Rajam, Andhra Pradesh


 Method 2 (Actions within FORMs):
- The second technique we've seen for triggering a Function in response to a
mouse action is to place an onClick Event Handler inside a button type form
element, like this:
<FORM>
<INPUT TYPE="button" onClick="doSomething()">
</FORM>
- While any JavaScript statement, methods, or functions can appear inside the
quotation marks of an Event Handler, typically, the JavaScript script that
makes up the Event Handler is actually a call to a function defined in the
header of the document or a single JavaScript command. Essentially, though,
anything that appears inside a command block (inside curly braces {}) can
appear between the quotation marks.
- For instance, if you have a form with a text field and want to call the function
checkField() whenever the value of the text field changes, you can define
your text field as follows:
<INPUT TYPE="text" onChange="checkField(this)">
- Nonetheless, the entire code for the function could appear in quotation
marks rather than a function call:
<INPUT TYPE="text" onChange="if (this.value <= 5) {
alert("Please enter a number greater than 5");
}">

- To separate multiple commands in an Event Handler, use semicolons


<INPUT TYPE="text" onChange="alert(‘Thanks for the entry.’);
confirm(‘Do you want to continue?’);">
- The advantage of using functions as Event Handlers, however, is that you
can use the same Event Handler code for multiple items in your document
and, functions make your code easier to read and understand.
 Method 3 (BODY onLoad & onUnLoad):
- The third technique is to us an Event Handler to ensure that all required
objects are defined involve the onLoad and onUnLoad. These Event
Handlers are defined in the <BODY> or <FRAMESET> tag of an HTML file
and are invoked when the document or frameset are fully loaded or
unloaded. If you set a flagwithin the onLoad Event Handler, other Event
Handlers can test this flags to see if they can safely run, with the knowledge
that the document is fully loaded and all objects are defined. For example:
<SCRIPT>
var loaded = false;
function doit() {
// alert("Everything is \"loaded\" and loaded = " + loaded);
alert('Everything is "loaded" and loaded = ' + loaded);
}
</SCRIPT>
<BODY onLoad="loaded = true;"> -- OR --
<BODY onLoad="window.loaded = true;">
<FORM>
<INPUT TYPE="button" VALUE="Press Me"

GMRIT, Rajam, Andhra Pradesh


onClick="if (loaded == true) doit();"> -- OR --
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (window.loaded == true) doit();"> -- OR --
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (loaded) doit();">
</FORM>
</BODY>
- The onLoad Event Handler is executed when the document or frameset is
fully loaded, which means that all images have been downloaded and
displayed, all subframes have loaded, any Java Applets and Plugins
(Navigator) have started running, and so on. The onUnLoad Event Handler is
executed just before the page is unloaded, which occurs when the browser is
about to move on to a new page. Be aware that when you are working with
multiple frames, there is no guarantee of the order in which the onLoad
Event Handler is invoked for the various frames, except that the Event
Handlers for the parent frame is invoked after the Event Handlers of all its
children frames
- Event Handlers

Note: Input focus refers to the act of clicking on or in a form element or


field. This can be done by clicking in a text field or by tabbing between text
fields.

GMRIT, Rajam, Andhra Pradesh


- Which Event Handlers Can Be Used

GMRIT, Rajam, Andhra Pradesh


➢ Object Hierarchy

GMRIT, Rajam, Andhra Pradesh


GMRIT, Rajam, Andhra Pradesh
❖ Array Object
o The Array object is used to store multiple values in a single variable.
o Create an Array
- The following code creates an Array object called myCars:
var myCars=new Array();
o There are two ways of adding values to an array (you can add as many values as
you need to define as many variables you require).
1:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
o You could also pass an integer argument to control the array's size:
var myCars=new Array(3);
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";2:
var myCars=new Array("Saab","Volvo","BMW");
o Note: If you specify numbers or true/false values inside the array then the type
of variables will be numeric or Boolean instead of string.
o Access an Array
 You can refer to a particular element in an array by referring to the name of
the array and the index number. The index number starts at 0.

GMRIT, Rajam, Andhra Pradesh


 The following code line:
document.write(myCars[0]);
- will result in the following output:
Saab
 Modify Values in an Array
To modify a value in an existing array, just add a new value to the array with
a specified index number:
myCars[0]="Opel";
- Now, the following code line:
document.write(myCars[0]);
- will result in the following output:
Opel
❖ Date Object
o Create a Date Object
 The Date object is used to work with dates and times.
 The following code create a Date object called myDate:
var myDate=new Date()
 Note: The Date object will automatically hold the current date and time as
its initial value!
 Set Dates
- We can easily manipulate the date by using the methods available for the
Date object.
- In the example below we set a Date object to a specific date (14th January
2010):
var myDate=new Date();
myDate.setFullYear(2010,0,14);
- And in the following example we set a Date object to be 5 days into the
future:
var myDate=new Date();
myDate.setDate(myDate.getDate()+5);
- Note: If adding five days to a date shifts the month or year, the changes are
handled automatically by the Date object itself!
 Compare Two Dates
- The Date object is also used to compare two dates.
- The following example compares today's date with the 14th January 2010:
var myDate=new Date();
myDate.setFullYear(2010,0,14);
var today = new Date();
if (myDate>today)
{
alert("Today is before 14th January 2010");
}
else
{
alert("Today is after 14th January 2010");
}

GMRIT, Rajam, Andhra Pradesh


❖ Math Object
o The Math object allows you to perform mathematical tasks.
o The Math object includes several mathematical constants and methods.
o Syntax for using properties/methods of Math:
var pi_value=Math.PI;
var sqrt_value=Math.sqrt(16);
o Note: Math is not a constructor. All properties and methods of Math can be
called by using Math as an object without creating it.
o Mathematical Constants
- JavaScript provides eight mathematical constants that can be accessed from
the Math object. These are: E, PI, square root of 2, square root of 1/2, natural
log of 2, natural log of 10, base-2 log of E, and base-10 log of E.
- You may reference these constants from your JavaScript like this:
Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E
o Mathematical Methods
- In addition to the mathematical constants that can be accessed from the
Math object there are also several methods available.
- The following example uses the round() method of the Math object to round
a number to the nearest integer:
document.write(Math.round(4.7));
The code above will result in the following output:
5
- The following example uses the random() method of the Math object to
return a random number between 0 and 1:
document.write(Math.random());
The code above can result in the following output:
0.4218824567728053
- The following example uses the floor() and random() methods of the Math
object to return a random number between 0 and 10:
document.write(Math.floor(Math.random()*11));
The code above can result in the following output:
4

❖ String object
o The String object is used to manipulate a stored piece of text.
o Examples of use:
o The following example uses the length property of the String object to find the
length of a string:
var txt="Hello world!";
document.write(txt.length);
The code above will result in the following output:
12

GMRIT, Rajam, Andhra Pradesh


o The following example uses the toUpperCase() method of the String object to
convert a string to uppercase letters:
var txt="Hello world!";
document.write(txt.toUpperCase());
The code above will result in the following output:
HELLO WORLD!
Lecture - 6
➢ Document Object Model
❖ The Document object represents the entire HTML document and can be used to
access all elements in a page.
❖ The Document object is part of the Window object and is accessed through the
window.document property.
❖ When a web page is loaded, the browser creates a Document Object Model of the
page.
❖ The HTML DOM model is constructed as a tree of Objects:

o Window Object: Window Object is object of the browser which is always at top
of the hierarchy. It is like an API that is used to set and access all the properties
and methods of the browser. It is automatically created by the browser.
o Document object: When an HTML document is loaded into a window, it
becomes a document object. The ‘document’ object has various properties that
refer to other objects which allow access to and modification of the content of
the web page. If there is a need to access any element in an HTML page, we
always start with accessing the ‘document’ object. Document object is property
of window object.
o Form Object: It is represented by form tags.
o Link Object: It is represented by link tags.
o Anchor Object: It is represented by a href tags.
o Form Control Elements: Form can have many control elements such as text
fields, buttons, radio buttons, checkboxes, etc.
❖ DOM Methods
o DOM provides various methods that allows users to interact with and
manipulate the document. Some commonly used DOM methods are:
- write(“string”): Writes the given string on the document.
- getElementById(): returns the element having the given id value.
- getElementsByName(): returns all the elements having the given name
value.

GMRIT, Rajam, Andhra Pradesh


-getElementsByTagName(): returns all the elements having the given
tag name.
- getElementsByClassName(): returns all the elements having the given
class name.
o Example
- The following example changes the content (the innerHTML) of the <p>
element with id="demo":
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
- Result
My First Page
Hello World!
❖ Document Object Collections

❖ Document Object Properties

➢ Browser Object Model


❖ Browser Object Model (BOM) is a programming interface JavaScript tool for
working with web browsers. This enables access & manipulation of the browser
window, frames, and other browser-related objects by facilitating the JavaScript
code.

GMRIT, Rajam, Andhra Pradesh


❖ The main object is “window,” which helps to interact with the browser. By default,
you can call window functions directly.
window.alert(" Hey Prabha");
// Same as
alert(" Hey Prabha ");

❖ Browser Object Model Types

Types Description

Window Object Represents the browser window and serves as the main tool for interaction
Model within the Browser Object Model (BOM).

History Object Enables navigation control by keeping track of the user’s browsing history in
Model the Browser Object Model (BOM).

Screen Object Offers information about the user’s screen, like its size, within the Browser
Model Object Model (BOM).

Navigator Object Provides details about the user’s browser and system characteristics within
Model the Browser Object Model (BOM).

Location Object Manages the current web address (URL) and allows changes within the
Model Browser Object Model (BOM).

❖ Window Size
o You can use two properties to find out the dimensions of the browser window,
and both provide the measurements in pixels:

Window Size Description

window.innerHeight This gives you the vertical size or height of the browser window in pixels.

This gives you the horizontal size or width of the browser window in
window.innerWidth
pixels.

❖ Other Window Methods


Window Methods Descriptions

This method is used to open a new tab or window with the specified URL
window.open()
and name.

GMRIT, Rajam, Andhra Pradesh


Window Methods Descriptions

This method is used for closing a certain window or tab of the browser that
window.close()
was previously opened by the window.open( ) method.

This method is used in the window to move the window from the left and
window.moveTo()
top coordinates.

window.resizeTo() This method is used to resize a window to the specified width and height

❖ Advantages & Disadvantages of BOM


o Advantages
- User Interaction: BOM allows websites to show alerts, prompts, and
confirmations, making them more interactive.
- Navigation Control: It also helps to manage going back or forward in your
browsing history using tools like ‘history.’
- Browser Details: BOM gives information about your browser through the
‘navigator’ tool, helping to adjust content for different browsers and
systems.
- Location Management: Using the ‘location’ tool, BOM lets websites change
web addresses for dynamic content and easy redirection.
o Disadvantages
- Browser Compatibility: It may work differently in various browsers, causing
compatibility issues.
- Security Concerns: Some BOM features, like pop-ups, can be exploited for
security risks.
- Client-Side Dependency: It relies heavily on the client side, hence affecting
performance.
- Limited Standardization: It lacks a standardized specification, leading to
variations in implementation.
❖ Sample Questions

Remember

1. Define Fuctions.
2. List out advantages of JavaScript

Understanding

1. Explain the concept of Array Intialization and declaration with example


2. Discuss about Function types

9. Stimulating Question (s)

1. Design a dynamic web page for Registration with validations


2. Design a web page with export and importing modules concept
GMRIT, Rajam, Andhra Pradesh
10. Mind Map

11. Student Summary

At the end of this session, the facilitator (Teacher) shall randomly pic-up few students to
summarize the deliverables.

12. Reading Materials


❖ Advanced Java Script Speed up web development with powerful and benefits of Java Script,
Zachary Shute, Packt Publishers
❖ https://www.tutorialspoint.com/javascript/index.htm
❖ https://www.geeksforgeeks.org/javascript/

13. Scope for Mini Project

❖ Develop a dynamic web page for Registration with validations.

GMRIT, Rajam, Andhra Pradesh

You might also like