Unit III –Client-Side Processing and Scripting
JavaScript Introduction – Variables and Data
Types – Statements – Operators – Literals –
Functions – Objects – Arrays – Built-in Objects
– Regular Expression, Exceptions, Event
handling, Validation – JavaScript
Debuggers.
3.
JavaScript – Introduction
JavaScriptcan 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 will save the
server
from extra processing.
•
•
•
•
4.
JavaScript – Introduction
Thereare THREE ways that JavaScript can be used within an
HTML file. It can be
1. Put inside <script> tags within the <head> tag (header
scripts),
2. Put inside <script> tags within the <body> tag (body
scripts), or
3. Called directly when certain events occur.
5.
JavaScript – Features
•JavaScript is used in the client side for validating data.
• JavaScript is embedded in HTML.
• JavaScript has no user interfaces. It relies heavily on HTML to provide user
interaction.
• JavaScript is browser dependent.
• JavaScript as a loosely typed language. JavaScript is more flexible. It is
possible to work with variables whose type is not known.
• JavaScript is an Interpreted Language.
6.
JavaScript – Features
•JavaScript is an object-based language. An extension of object-
oriented programming language. Objects in JavaScript encapsulate data &
methods. JavaScript object model is instance based & not inheritance
based.
• JavaScript is event-driven. Code will be in response to events generated by
the user or the system. JavaScript is equipped to handle events.
• HTML objects such as buttons and text boxes are equipped to support
event handlers. Event handlers are functions that are invoked in response to
a message generated by the system or user.
7.
JavaScript – HeaderScript
<html >
<head>
<title
>Print
ing
Multi
ple
Lines
in a
Dialo
g
Box</
title>
<script type = "text/javascript">
document.write( "Welcome to <br/> JavaScript
</script>
</head>
<body>
</body>
</html>
Programming!" );
document.write – used to display contents on web page.
8.
JavaScript – BodyScript
<html>
<head>
<title>Java Script Program – Alert</title>
</head>
<body>
<script type = “text/javascript">
window.alert(" <h1>hello, welcome to javascript! </h1>
");
</script>
</body>
</html>
window.alert – gives the alert message.
9.
JavaScript – GettingInput from User
window.prompt –
to get data
used to prompt the user
<html>
<head><title>Input from
user</title>
<script type="text/javascript">
var fname,lname,name;
fname=window.prompt("Enter the first name");
lname=window.prompt("Enter the last name");
name=fname+lname;
document.write("<h1>My name ist"
+name+"</h1>");
window.alert(name);
</script>
</head>
<body>
<p>refresh the page to restart script</p>
</body></html>
10.
JavaScript – Comments
•Single line comments start with //.
• Multi-line comments start with /* and end with */.
• Adding // in front of a code line changes the code lines from an executable
line to a comment.
11.
JavaScript – Variables
Variablesare containers for storing data (storing data
values).
Example:
var x = 5;
var y = 6;
var z = x + y;
12.
JavaScript
String: var s= “india”
– Variables
Number: var n = 0, 100, 3.14159
Boolean: var flag = false or true
Object: var d = new Date();
Function: var Greet = function sayHello() {alert(‘Hello’)}
• JavaScript is a weakly typed language. (i.e.) A simple assignment is
sufficient to change the variable type.
• The typeof keyword can be used to check the current variable type.
13.
JavaScript – Variables
JavaScriptVariable Scope
• Global Variables: It can be defined anywhere in your JavaScript
code.
• Local Variables: A local variable will be visible only within a
function
where it is defined. Function parameters are always local tothat function.
Example:
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!-- var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local
variable
document.write(myVar); }
//-->
</script>
</body>
</html>
14.
JavaScript – ReservedWords
abstract else instanceof switch
boolean enum int synchronized
break export interface this
byte extends long throw
case false native throws
catch final new transient
char finally null true
class float package try
const for private typeof
continue function protected var
debugger goto public void
default if return volatile
delete implements short while
do import static with
double in super
15.
JavaScript – DataTypes
String: Sequence of characters enclosed in a set of single or double
quotes
•
• Number: Integer or floating point numbers
• Bigint: Used to store integer values that are too big to be represented by a normal
JavaScript Number. Ex: let x = BigInt("123456789012345678901234567890");
• Boolean: Either true/false or a number (0 being false) can be used for Boolean
values
• Undefined: Is a special value assigned to an identifier after it has been declared but
before a value has been assigned to it
• Null: No value assigned which is different from a 0
• Object: Entities that typically represents elements of a HTML page
16.
JavaScript – DataTypes
Object Datatypes
Object: JavaScript objects are written with curly braces {}.
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Array: JavaScript arrays are written with square brackets.
const cars = ["Saab", "Volvo", "BMW"];
Date: Used to get year, month and day.
17.
JavaScript – Statements
•JavaScript statements are the commands to tell the
browser to what action to
perform. Statements are separated by semicolon (;).
• JavaScript statement constitutes the JavaScript code which is translated by the
browser line by line.
• Expression statement: Any statement that consists entirely of an
expression
– Expression: code that represents a value
• Block statement: One or more statements enclosed in { }
braces
• Keyword statement: Statement beginning with a keyword, e.g., var or if
• Example: document. getElementById("demo").
18.
JavaScript – Operators
TypeOperator Meaning Example
Arithmetic
+ Addition or Unary Plus c = a+b
- Subtraction or Unary Minus d = -a
* Multiplication c = a*b
/ Division c = a/b
% Modulo c = a%b
Relational
< Less than a < 4
> Greater than b > 10
<= Less than equal to b <= 10
>= Greater than equal to a >= 5
== Equal to x == 100
!= Not equal to m != 8
Logical
&& And operator 0 && 1
|| Or operator 0 || 1
Assignment = Is assigned to a = 5
Increment ++ Increment by one ++i or i++
Decrement -- Decrement by one --k or k--
19.
JavaScript
• Literals aresimple constants.
– Literals
Example:
34
3.14159
“frog beaks”
‘/nTitle/n’
true
Character Meaning
b backspace
f form feed
n new line
r carriage return
t tab
backslash character
" double quote
‟ Single quote
ddd Octal number
xdd Tow digit hexadecimal number
xdddd Four digit hexadecimal number
20.
JavaScript – ControlStatements
Statement Syntax Example
if-else
if (condition)
statement;
else
statement;
if (a>b)
document.write(“a is greater than b”);
else
document.write(“b is greater than a”);
while
while(condition) {
statements;
}
while(i<5) {
i=i+1;
document.write(“value of I”+i);
}
do…while
do {
Statements;
}
while(conditio
n);
do{
i=i+1;
document.write(“value of I”+i)
}while(i<5);
21.
JavaScript – ControlStatements
Statement Syntax Example
for
for(initialization; testcondition;
stepcount) {
Statements;
}
for(i=0; i<5; i++){
document.write(i);
}
Switch…Case
switch(expression) {
case 1:statements
break;
case 2: statements
break;
….
default: statements
}
switch(choice)
{
case 1:c=a+b;
break;
case 2:c=a-b;
break;
}
JavaScript – Functions
•A JavaScript function is a block of code designed to perform a
particular task.
• A function is a group of reusable code which can be called anywhere in
your program.
Syntax
<script type = "text/javascript">
function functionname (parameter-list) {
…..
statements
}
</script>
JavaScript – Functions
GlobalFunctions
• The top-level function in JavaScript
that
These functions use the built-in objects.
are independent of any specific object.
• encodeURI(uri): Used to encode the URI. This function encodes special characters
except , / ? : @ & = + $ #.
• decodeURI(uri): Decodes the encoded URI.
• parseInt(string,radix): Parse a string and returns the integer value.
• parseFloat(string,radix): Used to obtain the real value from the string.
• eval(string): Used to evaluate the expression.
JavaScript – Arrays
•Array is a collection of similar type of elements which can be referred by
a common name.
• Any element in an array is referred by an array name followed by index
(i.e., [ ]).
• The particular position of element in an array is called array index or
subscript.
31.
JavaScript – Arrays
•Array Declaration: The array can be created using Array
object.
var ar = new Array(10);
• Array Initialization
var ar = new Array (11,22,33,44,55);
var fruits = new Array( "apple", "orange","mango" );
32.
JavaScript – Arrays
•Array Properties:
Properties Description
constructor Returns a reference to the array function that created the object.
index Represents the zero-based index of the match in the string
input Only present in arrays created by regular expression matches.
length Reflects the number of elements in an array.
prototype Allows you to add properties and methods to an object
33.
JavaScript – Arrays
•Array Methods:
Properties Description
concat() Returns a new array comprised of this array joined with other
array(s) and/or value(s)
every() Returns true if every element in this array satisfies the provided
testing function.
filter() Creates a new array with all of the elements of this array for which
the provided filtering function returns true.
forEach() Calls a function for each element in the array.
indexOf() Returns the first (least) index of an element within the array equal to
the specified value, or -1 if none is found.
join() Joins all elements of an array into a string.
lastIndexOf() Returns the last (greatest) index of an element within the array equal
to the specified value, or -1 if none is found.
34.
JavaScript – Arrays
•Array Methods:
Properties Description
map() Creates a new array with the results of calling a provided function on
every element in this array.
pop() Removes the last element from an array and returns that element.
push() Adds one or more elements to the end of an array and returns the new
length of the array.
reduce() Apply a function simultaneously against two values of the array (from
left-to-right) as to reduce it to a single value.
reduceRight() Apply a function simultaneously against two values of the array (from
right-to-left) as to reduce it to a single value.
reverse() Reverses the order of the elements of an array
shift() Removes the first element from an array and returns that element.
slice() Extracts a section of an array and returns a new array.
35.
JavaScript – Arrays
•Array Methods:
Properties Description
some() Returns true if at least one element in this array satisfies the provided
testing function
toSource() Represents the source code of an object
sort() Sorts the elements of an array
splice() Adds and/or removes elements from an array
toString() Returns a string representing the array and its element
Unshift() Adds one or more elements to the front of an array and returns the
new length of the array
36.
JavaScript – Arrays
Writea JavaScript to print the largest and smallest values
among 10 elements of an
array.
37.
JavaScript – Arrays
Writea JavaScript to print the largest and smallest values
among 10 elements of an
array.
38.
JavaScript – DocumentObject Modeling
• Defining the standard for accessing and manipulating HTML, XML
and other scripting languages.
• DOM is a set of platform independent and language neutral Application
Programming Interface (API) which describes how to
and
access and
manipulate the
documents.
information stored in XML, HTML JavaScript
39.
JavaScript – DocumentObject Modeling
DOM Methods
Method Description
getElementById Used to obtain the specific element which specified by some id
within the script
createElement Used to create an element node
createTextNode Used for creating text node
createAttribute Used for creating attribute
appendChild For adding a new child to specified node
removeChild For removing a new child to specified node
getAttribute To return a specified attribute value
setAttribute To set or change the specified attribute to the specified value
40.
JavaScript – DocumentObject Modeling
DOM Properties
Property Description
attributes Used to get the attribute nodes of the node
parentNode To obtain the parent node of the specific node
childNodes To obtain the child nodes of the specific parent node
innerHTML To get the text value of a node
JavaScript – Objects
•The web designer can create an object and can set its properties as per
their requirements.
• The object can be created using new expression.
• Syntax:
Myobj = new Object();
43.
JavaScript – Build-inObjects
Math Object
• The math object provides
constants and functions.
properties and methods for mathematical
• Math is not a constructor.
• All the properties and methods of Math are static and can be called
by using Math as an object without creating it.
• Example
document.write(math.min(3,4,5));
document.write(math.sin(30));
44.
JavaScript – Build-inObjects
Math Methods
Methods Description
abs(num) Returns the absolute value of a number
sin(num), cos(num),
tan(num) Returns the sine, cosine, tangent() of a number
min(a,b), max(a,b) Returns the smallest / largest of zero or more numbers
round(num) Returns the value of a number rounded to the nearest integer
random() Returns a pseudo-random number between 0 and 1
exp(num) Returns EN, where N is the argument, and E is Euler's
constant, the base of the natural logarithm
ceil(num), floor(num) Returns the largest integer less than or equal to a number
pow(a,b) Returns base to the exponent power, that is, base exponent
sqrt(num) Returns the square root of a number
log(num) Returns the natural logarithm (base E) of a number
45.
JavaScript – Build-inObjects
Number Object
• Represents numerical data, either integers or floating-point
numbers.
• Syntax:
var val = new Number(number);
• Properties
Methods Description
MAX_VALUE Display largest possible number
MIN_VAUE Display smallest possible number
NaN Display NaN, When not a number
PI Display the value PI
POSITIVE_INFINITY Display the positive infinity
NAGATIVE_INFINITY Display the negative infinity
46.
JavaScript – Build-inObjects
Date Object
• Used to obtain the date and time.
• Date objects are created with the new
Date( ).
• Syntax:
var my_date = new Date( )
47.
JavaScript – Build-inObjects
Date Object
Methods Description
getTime() Return the number of milliseconds. [1970 to current year]
getDate() Return the current date based on computers local time
getUTCDate() Return the current date obtained from UTC
getDay() Return the current day. [0 – 6 => Sunday – Saturday]
getUTCDay() Return the current day based on UTC. [0 – 6 => Sunday – Saturday]
getHours() Returns the hour value ranging from 0 to 23, based on local time
getUTCHours() Returns the hour value ranging from 0 to 23, based on UTC time zone
getMilliseconds() Returns the milliseconds value ranging from 0 to 999, based on local time
getUTCMilliseconds() Returns the milliseconds value ranging from 0 to 999, based on UTC
getMinutes() Returns the minute value ranging from 0 to 59, based on local time
getUTCMinutes() Returns the minute value ranging from 0 to 59, based on UTC time zone
getSeconds() Returns the second value ranging from 0 to 59, based on local time
getUTCSeconds() Returns the second value ranging from 0 to 59, based on UTC time zone
setDate(value) To set the desired date using local or UTC timing zone
setHour(hr,
minute,second,ms) To set the desired time using local or UTC timing zone
48.
JavaScript – Build-inObjects
String Object
• A collection of characters
• It wraps Javascript's string primitive data type with a number of helper methods.
• Syntax:
var val = new String(string);
49.
JavaScript – Build-inObjects
String Object
Methods Description
concat(str) Concatenates the two strings
charAt(index_val) Return the character specified by value index_val
substring(begin, end) Returns the substring specified by begin and end character
toLowerCase() Used to convert all uppercase letters to lowercase
toUpperCase() Used to convert all lowercase letters to uppercase
valueOf() Returns the value of the string
50.
JavaScript – Build-inObjects
Boolean Object
• Represents two values, either "true" or "false".
• If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the
empty string (""), the object has an initial value of false.
the object
Methods Description
toSource() Returns a string containing the source of the Boolean object
toString()
Returns a string of either "true" or "false" depending upon the value of
valueOf() Returns the primitive value of the Boolean object
51.
JavaScript
Object
– Build-in Objects
Window
_parent– URL is loaded in parent window
Methods Description
alert(String) Displays the alert box with some message and OK button
confirm(String) Displays the alert box with some message and OK button and Cancel button
prompt(String) Displays a dialog box which allows the user to input some data
open(URL, width,
height)
Opens a new window with specified URL
_blank – URL is loaded in new window
_self – URL replaces currently opened window
_top – URL replaces the currently opened frameset
close() Close the current window
moveBy() Move the window from the current position to some other position
moveTo() Moves the window to specific position
resizeBy() Resizes the window by the specified pixels
resizeTo() Resizes the window by the specified width and height
52.
JavaScript – RegularExpression
• A regular expression is a special text string that defines the search
pattern.
• It is a logical expression.
• Create a regular expression pattern using forward slash /.
• It is a powerful pattern-matching and search-and-replace functions on
text.
• Syntax:
var pat = /pattern/
53.
JavaScript – RegularExpression
Special Characters Description
. Any character expect new line
? 0 or 1
* 0 or more occurrence
+ 1 or more occurrence
^ Start of the String
$ End of the String
[abc] Any of the characters a, b, or c
[A-Z] Any character from uppercase A to uppercase Z
54.
JavaScript – RegularExpression
Methods Description
exec Tests for a match in a string. If it finds a match, it returns a
result
array, otherwise it returns null.
test Tests for a match in a string. If it finds a match, it returns
true,
otherwise it returns false.
match Tests for a match in a string. It returns an array of information or null
on a mismatch.
search Tests for a match in a string. It returns the index of the match, or -1
if
the search fails.
replace Tests for a match in a string and replaces the matched substring with
a replacement substring.
split Uses the regular expression or a fixed string to break a string into an
array of substring.
JavaScript – RegularExpression
X +
0 Phone Number Checking X 0 Phone Number Checking v
0. c!:J '{:( a
K :
� � C CD File fVolumes/Kav1ya/Academ1cs/lT2253%20-%20WE/Examples/JavaScript%20Examples/phoneno.html
0 Sci-Hub I The ma e Tamil Jothida Pala ,j Microsoft Teams 0 � AIRCC Publishing � Machine Learning
Enter Phone Number: I (333)
5555555
Country Code:
1�3_3
�
Phone Number: �5 5_5 �
Click
59.
JavaScript – Exceptions
•Exception handling is a mechanism that handles the
runtime errors so that
the normal flow of the application can be maintained.
Statements:
• try: Test a block of code for errors
• catch: Handle the error
• throw: Create custom errors
• finally: Execute code, after try and catch, regardless of the result.
JavaScript – EventHandling
• Event: An activity that represents a change
mouse clicks, key press.
in the environment. Example:
• Event Handler: A script that gets executed in response to these events. It
enables the web document to respond that user activities through the
browser window.
• Event Registration: The process of connecting even handler to an event. It
can be done using two methods:
– Assigning the tag attributes
– Assigning the handler address to object properties
65.
JavaScript – EventHandling
Event Description Associated Tags
onclick The user clicks an HTML element <a>, <input>
ondbclick The user double clicks an HTML element <a>, <input>,
<button>
onmouseup The user releases the left mouse button Form elements
onmousedown The user clicks the left mouse button Form elements
onmousemove The user moves the mouse Form elements
onmouseover The user moves the mouse over an HTML element Form elements
onmouseout The user moves the mouse away from an HTML
element
Form elements
onkeydown The user pushes a keyboard key Form elements
onkeyup The user releases a key from keyboard Form elements
onkeypress The user presses the key button Form elements
66.
JavaScript – EventHandling
Event Description Associated Tags
onchange An HTML element has been changed <input>
<textarea>
<select>
onsubmit The user clicks the submit button <form>
onreset The user clicks the reset button <form>
onselect On selection <input>, <textarea>
onload After getting the document is loaded <body>
onunload The user exits the document <body>
67.
JavaScript – EventHandling
Syntax:
<input type = "button" name = “My_button” onclick = ”display()” />
Tag attribute
Event handler
JavaScript – Validation
•Various control objects are placed on the form.
• These control objects are called widgets.
• These widgets used in JavaScript are Textbox, Radio button, Check
box
and so on.
• In JavaScript, the validation of these widgets is an important task.
77.
JavaScript – Validation
Createthe following HTML form and do the following validation in Java
Script.
a) Check fields for not Empty
b)
c)
Email ID validation.
Numbers and special characters not allowed in First name and Last
name.
78.
JavaScript – Debuggers
•The standard traditional method of debugging the
JavaScript is using
alert() to display the values of the corresponding variables.
• Use API methods for debugging the JavaScript.
• Use log() function console API.
79.
JavaScript – Debuggers
•The standard traditional method of debugging the
JavaScript is using
alert() to display the values of the corresponding variables.
• Use API methods for debugging the JavaScript.
• Use log() function console API.
JavaScript – Examples
1.Design the simple calculator in JavaScript with the following operations:
Addition, Subtraction, Multiplication and Division.
Use JavaScript and HTML to create a page with two panes. The first pane (on
the
2.
left) should have a text area where HTML code can be typed by the user. The
pane on the right side should display the preview of the HTML code
user, as it would be seen in the browser.
Write a JavaScript to get the current hours as h and do the following:
If h>=0 and h<12 then print “Good Morning”
typed by the
3.
If h>=12 and h<4 then print “Good Noon”
If h>=4 and h<8 then print “Good Evening”
Otherwise print “Good night”