Unit - 4 (Client Side Scripting With JavaScript)
Unit - 4 (Client Side Scripting With JavaScript)
Syllabu
⚫ UNIT 4: Client Side Scripting with JavaScript (9 Hrs.)
o Structure of JavaScript s
Program
o Variables and Data Types
o Statements: Expression, Keyword, Block
o Operators
o Flow Controls, Looping, Functions
o Popup Boxes: Alert, Confirm, Prompt
o Objects and properties
o Constructors
o Arrays
o Built-in Objects: Window, String, Number, Boolean, Data, Math,
RegExp,
Form, DOM
o User Defined Objects
o Event Handling and Form Validation, Error Handling, Handling Cookies,
jQuery Syntax
o jQuery Selectors, Events and Effects
o Introduction to JSON
UNIT 4: CLIENT SIDE SCRIPTING
WITH JAVASCRIPT
JavaScrip
t
⚫ HTML to define the content of web pages; CSS to specify the
layout of web pages; JavaScript to program the behavior of web
pages.
⚫ JavaScript is a case sensitive scripting language.
⚫ A scripting language is a lightweight programming language.
⚫ JavaScript is usually embedded directly into HTML pages.
⚫ JavaScript is an interpreted language (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 & design.
⚫ Java (developed by Sun Microsystems) is a powerful and much
more complex programming language – in the same category
as C and C++.
What can 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 –
Syntax
⚫ Use JavaScript to write text on a web page:
<body>
<script type="text/javascript"> document.write("Hello World!");
</script>
</body>
⚫ Add HTML tags to the JavaScript
<body>
<script type="text/javascript"> document.write("<h1>HelloWorld!</h1>");
</script>
</body>
JavaScript –
<body> Comments
⚫ Single line comments
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
/ / Change heading:
document.getElementById("myH").innerHTML = "JavaScript
Comments";
/ / Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>
</body>
⚫ Multiple lines comments
<body>
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
/*
The code below will change the heading with id = "myH"
and the paragraph with id = "myP"
*/
document.getElementById("myH").innerHTML =
"JavaScript Comments";
document.getElementById("myP").innerHTML = "My first
paragraph.";
</script>
</body>
JavaScript –
Comments
Single line comments to prevent execution
⚫
<body>
< h2>JavaScript Comments</h2>
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first
paragraph.";
</script>
< p>The line starting with / / is not executed.< / p>
</body>
⚫ Multiple lines comments to prevent execution
<body>
<h2>JavaScript Comments</h2>
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
/*
document.getElementById("myH").innerHTML = "Welcome to my
Homepage";
document.getElementById("myP").innerHTML = "This is my first
paragraph.";
*/
document.getElementById("myP").innerHTML = "The comment-block is
What can JavaScript do? –
Example
<html>
<body>
1
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick='document.getElementById("demo").innerHTML =
"Hello JavaScript!"'>Click Me!</button>
</body>
</html>
Output:
What can JavaScript do? –
Example
<html>
<body>
2
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attribute values.</p>
<p>In this case JavaScript changes the value of the src (source) attribute of an
image.</p>
<button onclick="document.getElementById('myImage').src='https://s3-us-west-
2.amazonaws.com/s.cdpn.io/93927/pic_bulbon.gif'">Turn on the light</button>
<img id="myImage" src="https://s3-us-west-
2.amazonaws.com/s.cdpn.io/93927/pic_bulboff.gif" style="width:100px">
<button onclick="document.getElementById('myImage').src='https://s3-
us-west-
2.amazonaws.com/s.cdpn.io/93927/pic_bulboff.gif'">Turn off the
light</button>
</body>
</html>
What can JavaScript do? –
Example 2
Output:
Where to Insert
JavaScript?
⚫ JavaScript in Head
<html>
<head>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML = "Paragraph
changed.";
}
</script>
</head>
<body>
< h2>JavaScript in Head</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
Where to Insert
JavaScript?
Output:
Where to Insert
JavaScript?
⚫ JavaScript in Body
<html>
<body>
< h2>JavaScript in Body</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML = "Paragraph
changed.";
}
</script>
</body>
</html>
Where to Insert
JavaScript?
Output:
Where to Insert
JavaScript?
⚫ JavaScript in both Head & Body
<html>
<head>
<script type="text/javascript">
function message()
{alert("This alert box was
called with the onload
event"); }
</script>
</head>
<body onload="message()">
<script type="text/javascript">
document.write("This message
is written by JavaScript");
</script>
Where to Insert
JavaScript?
Output:
Using an External
JavaScript
⚫ If you want to run the same JavaScript on several pages, without
having to write the same script on every page, you can write a
JavaScript in an external file and save the file with a .js file
extension.
⚫ The external script cannot contain the <script></script> tags.
function myFunction()
{document.getElementById("demo").innerHTML = "Paragraph changed.";}
⚫ Using an External JavaScript
<body>
<h2>External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>(myFunction is stored in an external file called "myScript.js")</p>
<script src="myScript.js"></script>
</body>
JavaScript
Statements
JavaScript statements are commands to the browser.
⚫
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Hello Dolly.";
</script>
⚫ JavaScript code is a sequence of statements.
<p id="demo"></p>
<script>
var x, y, z; / / Statement 1
x = 5; / / Statement 2
y = 6; / / Statement 3
z = x + y; / / Statement 4
document.getElementById("demo").innerHTML ="The
value of z is " + z + ".";
</script>
⚫ JavaScript statements are separated with semicolon.
<p id="demo1"></p>
<script>
var a, b, c; a = 5;
b = 6;
c = a + b;
document.getElementById("demo1").innerHT
ML = c;
</script>
⚫ Multiple statement on one line is allowed.
<p id="demo1"></p>
<script>
var a, b, c; a = 5; b = 6; c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>
JavaScript
Statements
⚫ JavaScript statements can be grouped together in code blocks.
<button type="button" onclick="myFunction()">Click Me!</button>
< p id="demo1"></p >
<p id="demo2"></p>
<script>
function myFunction()
{ document.getElementById("demo1").innerHTML = "Hello
Dolly!";
document.getElementById("demo2").innerHTML = "How are
you?";
}
</script>
JavaScript
⚫ In Ja vaScript you cannot use these reserved words
as variables,Keywords
labels, or function names:
abstract arguments await* boolean
break byte case catch
char class* const continue
debugger default delete do
double else enum* eval
export* extends* false final
finally float for function
goto if implements import*
in instanceof int interface
let* long native new
null package private protected
public return short static
super* switch synchronized this
throw throws transient true
try typeof var void
volatile while with yield
JavaScript Data
Types
⚫ JavaScript data types are dynamic. i.e. the same variable
can be used to hold different data types.
var x; / / Now x is
x= undefined
5; / / Now x is a
x=
⚫ JavaScript Number expressions from left to right.
evaluates
"helo
⚫ Different / / Nowcan
sequences x isproduce
a different results.
"; x = 16 + String
var "Volvo"; // r esults:
16Volvo var x = "Volvo" + 16;
//results:Volvo16
var x = 16 + 4 + "Volvo";
// r esults: 20Volvo
⚫ In the last example, JavaScript treats 16 and 4 as numbers,
until it reaches “Volvo”. As a result, it adds 16 & 4 and then
JavaScript
Variables
⚫ JavaScript variables are containers for storing data values.
⚫ 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 & Y are two
different
variables).
o Variable names must begin with a letter or the
underscore character.
⚫ You can declare JavaScript variables with the var ,let and
const statement.
var x; var x=5;
var carname; var carname=“volvo”;
⚫ After the execution of the statements above, the variable
JavaScript
Operators
⚫ The assignment operator (=) assigns a value to a
variable.
var x = 10;
⚫ The addition operator (+) adds numbers.
var x=5; var y=2; var z = x+y;
⚫ The multiplication operator (*) multiplies numbers.
var x=5; var y=2; var z = x*y;
JavaScript Arithmetic
Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
JavaScript Arithmetic
Operators
The addition (+) operator
⚫
<body>
<p id="demo"></p>
<script>
var x = 5; var y = 2; var z = x + y;
document.getElementById("demo").innerHTML =
z;
</script>
</body>
⚫ The increment (++) operator
<body>
<p id="demo1"></p >
<p id="demo2"></p >
<script>
var y =
6;
document
.getEleme
ntById("d
emo1").in
nerHTM
JavaScript Assignment
Operators
Operator Example Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
**= x**=y x=x**y
JavaScript Assignment
Operators
⚫ The + = and **= operators
<body>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
var x = 10; x + = 5;
document.getElementById("demo1").innerHTML =
x; var y = 5; y **= 3;
document.getElementById("demo2").innerHTML =
y;
</script>
</body>
JavaScript String
Operators
⚫ The + operator can also be used to add (concatenate) strings.
var txt1=“John”; var txt2=“Doe”; var txt3=txt1+“ ”+txt2;
⚫ The result of txt3 will be:
John Doe
⚫ The + = assignment operator can also be used to
add (concatenate) strings.
var txt1=“What a very ”; txt1+=“nice day”;
⚫ The result of txt1 will be:
What a very nice day
⚫ Adding two numbers, will return the sum, but adding a
number and a string will return a string.
var x=5+5; var y=“5”+5; var z = “Hello”+5;
⚫ The result of x, y, & z will be:
10 55 Hello5
JavaScript Comparison
Operators
Operator Description
== Equal to
=== Equal value and equal type
!= Not equal
!== Not equal value or not equal type
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
? Ternary operator
JavaScript Comparison
Operators
⚫ The = = = and !== operators
<body>
<p id="demo1"></p >
<p id="demo2"></p >
<script>
var x =
5;
documen
t.getElem
entById(
"demo1"
).innerH
TML =
(x = = =
6);
var y =
JavaScript Logical
Operators
Operator Description
&& Logical and
|| Logical or
! Logical not
Popup Boxes – Alert
⚫ An alert box is often used if you want to make sure
Box
information comes through to the user.
⚫ When an alert box pops up, the user will have to click “OK”
to proceed.
alert(“sometext”);
⚫ For example: Output:
<head>
<script type="text/javascript">
function show_alert()
{alert("I am an alert box!"); }
</script>
</head>
<body>
<input onclick="show_alert()" value="Sho alert
type="button" w
box" / >
</body>
Popup Boxes – Confirmation
Box
A confirm box is often used if you want the user to verify or accept something.
⚫
⚫ When a confirm box pops up, the user will have to click either “OK” or “Cancel”
to proceed.
⚫ If the user clicks “OK”, the box returns true; and if the user clicks “Cancel”, the
box returns false.
confirm(“sometext”);
⚫ For example:
<head>
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Press a
button");
if (r==true) {document.write("You pressed OK!"); }
else { document.write("You pressed Cancel!"); }
}
</script>
</head>
<body>
<input type="button" onclick="show_confirm()"
value="Show confirm box" / >
Popup Boxes – Confirmation
Box
Output:
Popup Boxes – Prompt
page. Box
⚫ A prompt box is often used if you want the user to input a value before entering a
⚫ When a prompt box pops up, the user will have to click either “OK” or “Cancel”
to proceed after entering an input value.
⚫ If the user clicks “OK”, the box returns the input value; and if the user clicks
“Cancel”, the box returns null.
prompt(“sometext”, “defaultvalue”);
⚫ For example:
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{ var txt;
var person =
prompt("Please enter
your name:", "Harry
Potter");
if (person = = null | | person = = "") {txt = "User cancelled the
prompt.";} else {txt = "Hello " + person + "! How are you today?";}
document.getElementById("demo").innerHTML = txt;
Popup Boxes – Prompt
Box
Output:
Function
⚫ A function is simply a block of code with a name, which allows the block
of s
code to be called by other components in the scripts to perform certain tasks.
⚫ Functions can also accept parameters that they use to complete their task.
⚫ JavaScript actually comes with a number of built-in functions to accomplish
a variety of tasks.
⚫ Creating Custom Functions:
{function………………
name_of_function(argument1,argument2,…,arguments)
//Block of
code
} ………………
⚫ Calling Functions:
o There are two common ways to call a function; from an event handler and
from another function.
o Calling a function is simple. You have to specify its name followed by the pair
of
parenthesis
<Script Type = “Text/JavaScript”>
name_of_function(argument1,argument2,…,arguments)
A Simple
<html>
<head> Function
<script>
function myFunction()
{
document.getElementById("demo").innerHTML = "Hello
World!";
}
</script>
</head>
<body>
<p>When you click "Try it", a function will be called.</p>
<p>The function will display a message.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
A Simple
Function
Output:
Function that Returns a
Value
<html>
<body>
<p>This example calls a function which performs a calculation and
returns the result:</p>
<p id="demo"></p>
<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b)
{
Output:
return a *
b;
}
</script>
</body>
</html>
JavaScript
Objects
⚫ In JavaScript, almost everything is an object
⚫ Booleans, Numbers, and Strings (if defined with the
new keyword) can be objects.
⚫ Dates, Maths, Arrays, Functions, Regular expressions,
and Objects are always objects.
⚫ All JavaScript values, except primitives, are objects.
⚫ A primitive value is a value that has no properties
or methods.
⚫ A primitive data type is data that has a primitive value.
⚫ JavaScript defines 5 types of primitive data types:
string, number, boolean, null, & undefined.
⚫ Primitive values are immutable (they are hardcoded
and therefore cannot be changed).
JavaScript Objects
Properties
⚫ JavaScript variables can contain single values.
var person = “John Doe”;
⚫ Objects are variables too; but objects can contain many values.
⚫ The values are written as name:value pairs (name and value
separated by a colon). – creating an object using object literal
var person = {firstName:“John”, lastName:“Doe”, age:50,
eyeColor:“blue”};
⚫ A JavaScript object is a collection of named values.
⚫ The named values, in JavaScript objects, are called properties.
⚫ In above example, “firstName”, “lastName”, “age”, and “eyeColor”
are properties; whereas “John”, “Doe”, “50”, and “blue” are their
respective values.
Math Object in
⚫ The Math object allows you to perform mathematical tasks.
⚫ The JavaScript
Math object includes several mathematical constants
and
methods.
var pi_value = Math.PI;
var sqrt_value = M ath.sqrt(16);
⚫ All properties and methods of Math can be called by using Math
as
an object without creating it.
<body>
<h2>JavaScript Math.PI</h2>
<p>Math.PI returns the ratio of a circle's circumference to its diameter:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.PI;
</script>
</body>
Math Object in
JavaScript
Properties
Methods
⚫ Math.E – returns Euler’s ⚫ abs(x) – returns the absolute value of
x
number
⚫ ceil(x) – returns x, rounded upwards
(approx. 2.718) ⚫ to the nearest integer
floor(x) – returns x,
⚫ Math.LN2 – returns the rounded downwards to the nearest
⚫ integer
log(x) – returns the natural
natural logarithm of 2 (approx. logarithm
0.693) (base E) of x
⚫ Math.LN10 – returns the natural ⚫ max(x,y,z,…,n) – returns the number
with the highest value
logarithm of 10 (approx. ⚫ min(x,y,z,…,n) – returns the number
2.302) with the lowest value
⚫ ⚫ pow(x,y) – returns the value of x to
Math.LOG2E – returns the base-
the power of y
⚫
2 ⚫ sqrt(x) – returns the square root of x
Math.PI – returns PI
logarithm of E (approx. 1.442) ⚫ random(x) – returns a random
(approx.
⚫ Math.LOG10E – returns the number
3.14159) between 0 & 1
base- 10 logarithm of E ⚫ round(x) – rounds x to the
(approx. 0.434) nearest integer
Window Object in
JavaScript
⚫ The window object represents the browser’s window.
⚫ Two properties window.innerHeight and window.innerWidth can
be used to determine the size (in pixels) of browser
window.
<body>
<p id="demo"></p>
<script>
var w =
window.innerWidth; var
h = window.innerHeight;
var x =
document .getElementByI
d("demo");
x.innerHTML = "Browser
Date Object in
JavaScript
⚫ The Date object is used to work with dates and times.
⚫ Date objects are created with the Date() constructor.
⚫ Date object methods in JavaScript:
o getDate() – returns the day of the month (from 1 –
31)
o getDay() – returns the day of the week (from 0 – 6)
o getFullYear() – returns the year (four digits)
o getHours() – returns the hour (from 0 – 23)
o getMilliseconds() – returns the milliseconds (from 0 –
999)
o getMinutes() – returns the minutes (from 0 – 59)
o getMonth() – returns the month (from 0 – 11)
o getSeconds() – returns the seconds (from 0 – 59)
Date Object in
<html>
<body>
JavaScript
<h2>JavaScript new Date()</h2>
<p id="demo"></p>
<script>
var d = new Date();
document.get ElementById("demo").innerHTML = d;
//document.get ElementById("demo").innerHTML = d.getDate();
//document.get ElementById("demo").innerHTML = d.getDay();
//document.get ElementById("demo").innerHTML = d.getFullYear();
//document.get ElementById("demo").innerHTML = d.getHours();
//document.get ElementById("demo").innerHTML = d.getMilliseconds();
//document.get ElementById("demo").innerHTML = d.getMinutes();
//document.get ElementById("demo").innerHTML = d.getMonths();
//document.get ElementById("demo").innerHTML = d.getSeconds();
</script>
</body>
</html>
String Methods in
JavaScript
⚫ String methods helps us to work with strings.
⚫ The length property returns the length of a string.
⚫ The indexOf() method returns the index of the
first
occurrence of a specified text in a string.
⚫ The search() method searches a string for a specified value
and returns the position of the match.
⚫ The slice() method extracts a part of a string and returns
the extracted part in a new string.
⚫ The replace() method replaces a specified value with
another value in a string.
⚫ The toUpperCase() method converts a string to upper case.
String Methods in
JavaScript
<html>
<body>
<h2>JavaScript String Properties</h2>
<p id="demo"></p>
<script>
var txt = "The quick brown fox jumps over the lazy dog.";
document.getElementById("demo").innerHTML =
txt.length;
/*
var pos = txt.indexOf("fox");
document.getElementById("demo").innerHTML = pos;
var pos = txt.search("jumps");
document.getElementById("demo").innerHTMLdocument.getElementById("demo").innerHTML
= pos; =
var txt =
var res = txt.slice(4,9); txt;
txt.toUpperCase();
document.getElementById("demo").innerHTML = res;
*/ txt = txt.replace("quick","slow");
var
</script>
document.getElementById("demo").innerHTML = txt;
</body>
</html>
Number Methods in
⚫ The Number(), can be used to convert JavaScript
JavaScript
variables to numbers.
⚫ The parseInt() parses a string and returns a whole number.
Spaces are allowed but only the first number is returned.
⚫ The parseFloat() parses a string and returns a number. Spaces are
allowed but only the first number is returned.
⚫ The toExponential() method returns a
string representing the number object in exponential
notation.
⚫ The toString() method returns a string representing the specified
object. The toString() method parses its first argument, and
attempts to return a string representation in the specified
radix.
⚫ The toFixed() returns a string, with the number written with a
specified number of decimals.
⚫ The toPrecision() returns a string, with a number written with
a
Number Methods in
<script type="text/ javascript">
JavaScript
x = true;
document.write(Number(x) +"<br>"); x =
false;
document.write(Number(x) +"<br>");
x = "10"
document.write(Number(x) +"<br>"); x =
"10 20"
document.write(Number(x) +"<br>");
document.write(parseInt("12") + "<br>");
document.write(parseInt("12.33") + "<br>");
document.write(parseInt("12 6") + "<br>" );
document.write(parseInt("12 years") + "<br>");
document.write(parseInt("month 12"));
</script>
Number Methods in
JavaScript
<body>
<p id="demo"></p>
<script>
var x = 9.656;
document.get E leme n tById("demo").innerHTML = x.toExpo
nen tial() + "<br>" + x.toExponential(2) + "<br>" +
x.toExponential(4) + "<br>" + x.toExponential(6);
</script>
</body>
Number Methods in
JavaScript
<script
type="text/javascript"> var
num = new Number(15);
document.write("num.toString() is: " + num.toString() +"<br />");
document.write("num.toString(2) is: " + num.toString(2)
+"<br />");
document.write("num.toString(4) is: " + num.toString(4) +"<br
/>");
</script>
Number Methods in
<body>
JavaScript
<p id="demo"></p>
<script>
var x = 9.656;
document.getElementById("demo").innerHTML =
x.toFixed(0) + "<br>" +
x.toPrecision() + "<br>"
+ x.toFixed(2) +
"<br>" +
x.toPrecision(2) +
"<br>" +
x.toFixed(4) + "<br>"
+ x.toPrecision(4) +
"<br>" + x.toFixed(6)
+ "<br>" +
x.toPrecision(6);
Boolean Methods in
JavaScript
⚫ A JavaScript Boolean represents one of two values: true or
false.
⚫ Boolean(5>3) and 5>3 returns same output as true.
<body>
<p>Display the value of Boolean(10 > 9):</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML = Boolean(5 > 3);
}
</script>
</body>
Boolean Methods in
⚫
JavaScript
Everything with a “value” is TRUE.
<body>
<p id="demo"></p>
<script>
var b1 = Boolean(100); var b2 = Boolean(3.14);
var b3 = Boolean(-15);
var b4 = Boolean("Hello"); var b5 = Boolean('false');
var b6 = Boolean(1 + 7 + 3.14);
document.getElementById("demo").innerHTML = "100 is " + b1 + "<br>" +
"3.14 is " + b2 + "<br>" + "-15 is " + b3 + "<br>" +
"Any (not empty) string is " + b4 + "<br>" + "Even the string 'false' is " +
b5 + "<br>" + "Any expression (except zero) is " + b6;
</script>
</body>
Boolean Methods in
JavaScript
⚫ Everything without a “value” is FALSE.
⚫ The Boolean value of 0 (zero) is FALSE.
⚫ The Boolean value of -0 (minus zero) is
FALSE.
⚫ The Boolean value of “ ” (empty string) is
FALSE.
⚫ The Boolean value of undefined is FALSE.
⚫ The Boolean value of null is FALSE.
⚫ The Boolean value of false is FALSE.
⚫ The Boolean value of NaN is FALSE.
Regular Expression in
JavaScript
⚫ Regular expressions are patterns used to match
character combinations in strings.
⚫ In JavaScript, regular expressions are also objects.
⚫ Regular expressions can be used to perform all types of
text search and text replace.
⚫ There are two main string methods: search() and replace().
⚫ search() method uses an expression to search for a
match, and returns the position of the match.
⚫ replace() method uses an expression to return a
modified string where the pattern is replaced.
Regular Expression in
JavaScript
<body>
<p id="demo"></p>
<script>
var str = "The quick brown fox jumps over the lazy
dog";
var n = str.search(/brown/i);
document.getElementById("demo").innerHTM
L = n;
</script>
</body>
Regular Expression in
JavaScript
<body>
<button onclick="myFunction()">Click to replace</button>
<p id="demo">The quick brown fox jumps over the lazy
dog</p>
<script>
function myFunction()
{
var str = document.getElementById("demo").innerHTML;
var txt = str.replace(/quick/i,"slow");
document.getElementById("demo").innerHTML
= txt;
}
</script>
Form Method
Property
⚫ It is used to change the method for sending form data.
⚫ The method property sets or returns the value of
method attribute in a form.
⚫ The syntax for setting the method property is:
formObject.method = get | post
⚫ get – appends the form-data to the
URL: URL?name=value&name=value (this is default).
⚫ post – sends the form-data as an HTTP post transaction.
Form Method
<body>
Property
<h2>Contact Us</h2>
<p>Please fill in this form and send us.</p>
<form action="form2-get.php" method="get">
<p>
<label
for="inputName">Name:<sup>*</sup></label>
<input type="text" name="name" id="inputName">
</p>
<p>
<label
for="inputEmail">Email:<sup>*</sup></label>
<input type="text" name="email" id="inputEmail">
</p>
<p>
<label for="inputSubject">Subject:</label>
<input type="text" name="subject" id="inputSubject">
</p>
<p>
<label for="inputComment">Message:<sup>*</sup></label>
<textarea name="message" id="inputComment" rows="5" cols="30"></textarea>
</p>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
Form Method
<body> Property
<h1>ThankYou</h1>
<p>Here is the information you have submitted:</p>
<ol>
<li><em>Name:</em> <?php echo $_GET["name"]?></li>
<li><em>Email:</em> <?php echo $_GET["email"]?></li>
<li><em>Subject:</em> <?php echo $_GET["subject"]?></li>
<li><em>Message:</em><?php echo
$_GET["message"]?></li>
</ol>
</body>
JavaScript
Arrays
⚫ An array is a special variable that can hold more than one value
at a time.
⚫ A list of items, storing the fruits in a single variable could be
like:
var fruit1
= “Apple”; var
fruit2 = “Banana”;
⚫ This might look possible for few items but isn’t feasible
for hundreds of item.
⚫ The solution is an array which can replace multiple declaration
in a single line like:
var fruits = [“Apple”,“Banana”];
⚫ To access an array element, we can refer to the index number
like:
document.getElementById("demo").innerHTML = fruits[0];
JavaScript
<html>
<body> Arrays
<p id="demo"></p>
<script>
var fruits = ["Apple", "Banana","Cherry","Orange","Mango"];
document.getElementById("demo").innerHTML = "The first element of an array is " +
fruits[0];
/ / document.getElementById("demo").innerHTML = "The last element
of an array is " +
fruits[fruits.length-1];
//document.getElementById("demo").innerHTML = "The elements of an array are " +
fruits;
//document.getElementById("demo").innerHTML = "The length of an array is " +
fruits.length;
/*
fruits.push("Lemon");
document.getElement
ById("demo").innerH
TML = "The
elements of an array
JavaScript Object
Constructors
⚫ Sometimes, we need a “blueprint” for creating many
objects of same “type”.
⚫ In such situation, the better option to create an “object
type” is to use an object constructor function.
⚫ All the objects of same type are created by calling
the constructor function with the new keyword.
JavaScript Object
Constructors
<html>
<body>
<h2>JavaScript Object Constructors </h2>
<p id="demo"></p>
<script>
/ / Constructor function for Person objects
function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor =
eye;
}
/ / Create two Person objects
var myFather = new Person("John", "Doe", 50,
"blue"); var myMother = new Person("Sally", "Rally",
48, "green");
/ / Display age
document.getElementById("demo").innerHTML = "My father is " + myFather.age + ". My mother is " +
myMother.age + ".";
/*
document.getElementById("demo").innerHTML = "My father name is " + myFather..firstName + " " +
myFather.lastName + ". He is " + myFather..age + " years old with " + myFather.eyeColor + " eyes. My mother
name is " + myMother.firstName + " " + myMother..lastName + ". She is " + myMother..age + " years old with "
+ myMother.eyeColor + " eyes.";
*/
</script>
</body>
JavaScript
Conditionals
⚫ Conditional statements are used to perform different
actions based on different conditions.
⚫ In JavaScript we have the following conditional statements:
o Use if to specify a block of code to be executed, if a
specified condition is true.
o Use else to specify a block of code to be executed, if the
same condition is false.
o Use else if to specify a new condition to test, if the
first
condition is false.
o Use switch to specify many alternative blocks of code to be
executed.
JavaScript
⚫ Syntax:
Conditionals
if (condition) {
(if)
/ / b lock of code to be executed if the condition is true
}
⚫ Example:
<body>
<p>Display "Good day!" if the hour is less than
18:00:</p>
<p id="demo">Good Evening!</p>
<script>
if (new Date().getHours() < 18)
{document.getElementById("demo").innerHTML =
day!";} "Good
</script>
</body>
JavaScript Conditionals
(else)
⚫ Syntax:
if (condition) {
// b lock of code to be executed if the condition is true
} else {
//block of code to be executed if the condition is false
}
⚫ Example:
<body>
<p>Click the button to display a time-based greeting:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var hour = new Date().getHours();
var greeting;
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
}
</script>
</body>
JavaScript Conditionals (else
if)
⚫ Syntax:
if (condition1) {
//block of code to be executed if the condition1 is true
} else if (condition2) {
//block of code to be executed if the condition1 is false and condtion2 is
true
} else {
//block of code to be executed if the condition1 is false and condition2 is
false
}
⚫ Example:
<body>
<p>Click the button to get a time-based greeting:</p>
< button onclick="myFunction()"> Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{ var greeting;
var time = new
Date().getHours();
if (time < 12) {
greeting = "Good
morning";
} else if (time < 18)
{ greeting = "Good
day";
} else {
greeting = "Good
evening";
}
JavaScript Conditionals
(switch)
Syntax: Example
<p id="demo"></p>
Switch (expression) <script>
{ var
day;
case x: switch (new
Date().getDay()) { case 0:
/ / b lock of day =
"Sunday";
code break; break;
case 1:
case y: day = "Monday";
break;
/ / b lock of case 2:
day =
code break; "Tuesday";
default: break;
case 3:
/ / b lock of day =
"Wednesday";
code break;
case 4:
} day =
"Thursday";
break;
case 5:
day =
"Friday";
break;
case 6:
JavaScript
Loops
⚫ Loops can execute a block of code a number of times.
⚫ JavaScript supports different kinds of loops:
o for – loops through a block of code a number of times
o for/in – loops through the properties of an object
o for/of – loops through the values of an iterable object
o while – loops through a block of
code while a specified condition is true
o do/while – also loops through a block of code while a
specified
condition is true
JavaScript Loop
(for)
⚫ Syntax:
for (statement1; statement2; statement3) {
// b lock of code to be executed
}
⚫ Statement 1 is executed (one time) before the execution of the code
block.
⚫ Statement 2 defines the condition for executing the code block.
⚫ Statement 3 is executed (every time) after the code block has been
executed.
⚫ Example:
<body>
<p id="demo"></p>
<script>
var num =
""; var i;
for (i = 0; i
< 5; i++)
{ num
JavaScript Loop
(for/in)
⚫ Example:
<body>
<p id="demo"></p>
<script>
var txt =
"";
var person = {fname:"John", lname:"Doe",
age:25}; var x;
for (x in person)
{
txt + = person[x] + " ";
}
document.getElementById("demo").innerHTML
= txt;
JavaScript Loop
(for/of)
⚫ Example:
<body>
<script>
var cars = ['BMW', 'Volvo',
'Mini']; var x;
for (x of cars)
{
document.write(x + "<br >");
}
</script>
</body>
JavaScript Loop
(while)
⚫ Syntax:
while (condition) {
// b lock of code to be executed
}
⚫ Example:
<body>
<p id="demo"></p>
<script>
var text =
""; var i =
0; while (i
< 10)
{
text += "<br>The number is " +
i; i++;
}
document.getElementById("demo").i
nnerHTML = text;
</script>
JavaScript Loop
do { (do/while)
⚫ Syntax:
Example 2
<html>
<head>
<script src="https:/ / code.jquery.com/ jquery-1.12.4.min.js"></ script>
<style>
p{ width: 100%; padding: 50px 0; text-align: center; font: bold 34px sans-serif; background: