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

JavaScript Lectuers Alhemah

The document provides an overview of JavaScript, highlighting its role as a lightweight scripting language for creating interactive web pages. It covers essential concepts such as JavaScript syntax, client-side scripting advantages and disadvantages, and the history of JavaScript and its implementations. Additionally, it explains how to incorporate JavaScript into HTML and outlines fundamental programming constructs like variables, conditionals, and loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

JavaScript Lectuers Alhemah

The document provides an overview of JavaScript, highlighting its role as a lightweight scripting language for creating interactive web pages. It covers essential concepts such as JavaScript syntax, client-side scripting advantages and disadvantages, and the history of JavaScript and its implementations. Additionally, it explains how to incorporate JavaScript into HTML and outlines fundamental programming constructs like variables, conditionals, and loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 144

Web Programming

JavaScript: Client-Side Scripting


-1-

Dr. Mohammed Alborihi


Objectives

1 What is JavaScript
2 Where Does Javascript
GO?

3 JavaScript Syntax

2
Section 1 of 3

WHAT IS JAVASCRIPT
What we've learned so far

Describes the Describes the


A web page…
content and appearance
that doesn't do
structure of and style of
anything
the page the page

4
What is JavaScript
 A lightweight programming language ("scripting language")
 Used to make web pages interactive

 Insert dynamic text into HTML (ex: user name)

 React to events (ex: page load, user click)

 Get information about a user's computer (ex: browser type)

 Perform calculations on user's computer (ex: form validation)

 JavaScript runs right inside the browser.

 JavaScript is dynamically typed.

 JavaScript is object oriented in that almost everything in the language


is an object. the objects in JavaScript are prototype-based rather than
class-based.

5
What isn’t JavaScript
 Although it contains the word Java, JavaScript and Java are vastly
different programming languages with different uses.
 Java is a full-fledged compiled, object-oriented language, popular for its
ability to run on any platform with a JVM installed.
 JavaScript is an interpreted language and it is one of the world’s most
popular languages, with fewer of the object-oriented features of Java,
and runs directly inside the browser, without the need for the JVM.

6
Why Study JavaScript?
 JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages.
2. CSS to specify the layout of web pages.
3. JavaScript to program the behaviour of web pages.

 Web pages are not the only place where JavaScript is used. Many
desktop and server programs use JavaScript. Node.js is the best
known. Some databases, like MongoDB and CouchDB, also use
JavaScript as their programming language.

7
Client-Side Scripting
Let the client compute

 The idea of client-side scripting refers to the client machine (i.e., the
browser) running code locally rather than relying on the server to
execute code and return the result.

8
Client-Side Scripting
 There are many advantages of client-side scripting:
 Processing can be offloaded from the server to client machines,

thereby reducing the load on the server.


 The browser can respond more rapidly to user events than

a request to a remote server ever could, which improves the user


experience.
 JavaScript can interact with the downloaded HTML in a way that

the server cannot, creating a user experience more like desktop


software than simple HTML ever could.

9
Client-Side Scripting
 The disadvantages of client-side scripting are mostly related to how
programmers use JavaScript in their applications.
 There is no guarantee that the client has JavaScript enabled.

 The idiosyncrasies between various browsers and operating

systems make it difficult to test for all potential client


configurations. What works in one browser, may generate an
error in another.
 JavaScript-heavy web applications can be complicated to debug

and maintain.

10
JavaScript History
 JavaScript was introduced by Netscape in their Navigator browser
back in 1996.

 JavaScript is in fact an implementation of a standardized scripting


language called ECMAScript.

 ES is short for ECMAScript. Every time you see ES followed by


a number, it is referencing an edition of ECMAScript.
 ES1: June 1997  ES8/ECMAScript 2017: June 2017
 ES2: June 1998  ES9/ECMAScript 2018: June 2018
 ES3: December 1999  ES10/ECMAScript 2019: June 2019
 ES4: Abandoned/ last draft 30 June 2003  ES11/ECMAScript 2020: June 2020
 ES5: December 2009  ES12/ECMAScript 2021: June 2021
 ES6/ECMAScript 2015: June 2015  ES13/ECMAScript 2022: June 2022
 ES7/ECMAScript 2016: June 2016

11
JavaScript Implementations
 Though JavaScript and ECMAScript are often used synonymously,
JavaScript is much more than just what is defined in ECMA-262.

 JavaScript is a scripting language designed to interact with web pages


and is made up of the following three distinct parts:
 The Core (ECMAScript), which is defined in ECMA-262 and provides the core
functionality
 The Document Object Model (DOM), which provides methods and interfaces for
working with the content of a web page.
 The Browser Object Model (BOM), which provides methods and interfaces for
interacting with the browser.

12
Section 2 of 3

WHERE DOES JAVASCRIPT GO?


Where does JavaScript go?
 JavaScript can be linked to an HTML page in a number of ways:
 Inline

 Embedded

 External

 Running JavaScript scripts in your browser requires downloading the


JavaScript code to the browser and then running it.

 Pages with lots of scripts could potentially run slowly, resulting in


a degraded experience while users wait for the page to load.

14
Inline JavaScript
 Inline JavaScript refers to the practice of including JavaScript code
directly within certain HTML attributes.
<a href="JavaScript:OpenWindow();"> more info </a>
<input type="button" onclick="alert('Are you sure?');" />

 Inline JavaScript is a real maintenance nightmare.

15
Embedded JavaScript
Better

 Embedded JavaScript refers to the practice of placing JavaScript code


within a <script> element.
<script type="text/javascript">
/* A JavaScript Comment */
alert ("Hello World!");
</script>

 Like with inline JavaScript, embedded scripts can be difficult to


maintain.

 You can place any number of scripts in an HTML document.

 Scripts can be placed in the <body>, or in the <head> section of an


HTML page, or in both.

16
External JavaScript
Better

 JavaScript supports this separation by allowing links to an external file


that contains the JavaScript.

 By convention, JavaScript external files have the extension .js.


<head>
<script type="text/JavaScript" src="greeting.js">
</script>
</head>

 External scripts are practical when the same code is used in many
different web pages.

 You can place an external script reference in <head> or <body>.

 This is the recommended way of including JavaScript scripts in your


HTML pages.

17
Section 3 of 3

JAVASCRIPT SYNTAX
JavaScript Syntax
 JavaScript syntax is the set of rules, how JavaScript programs are
constructed.

 We will briefly cover the fundamental syntax for the most common
programming constructs including:
 variables,

 assignment

 conditionals

 loops

 functions

 Then we will move to advanced topics such as objects and events.

19
Variables
 Variables in JavaScript are dynamically typed, meaning a variable can
be an integer, and then later a string, then later an object, if so
desired.

 This simplifies variable declarations, so that we do not require the


familiar type fields like int, char, and String. Instead we use var.

 Assignment can happen at declaration-time by appending the value


to the declaration, or at run time with a simple right-to-left
assignment

20
Arithmetic Operators
 Arithmetic operators are used to perform arithmetic on numbers:
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
 Ex:
var x = 5; var x = 5; var x = 5;
var y = 2; var z = x ** 2; x++;
var z = x + y; // result is 25 var z = x;

21
Assignment Operators
 Assignment operators assign values to JavaScript variables.

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

22
String Operators
 The +, += operators can be used to add (concatenate) strings.

 Ex:
var txt1 = "John"; var txt1 = "What a very ";
var txt2 = "Doe"; txt1 += "nice day";
var txt3 = txt1 + " " + txt2;
The result of txt1 will be:
The result of txt3 will be: John Doe
What a very nice day

 If you add a number and a string, var x = 5 + 5;


the result will be a string. var y = "5" + 5;
var z = "Hello" + 5;

The result of x, y, and z will be:


10
55
Hello5

23
Comparison Operators
True or not True

Operator Description Matches (x=9)


== Equals (x==9) is true
(x=="9") is true
=== Exactly equals, including type (x===9) is true
(x==="9") is false
<,> Less than, Greater Than (x<5) is false

<= , >= Less than or equal, greater than or (x<=9) is true


equal
!= Not equal (4!=x) is true

!== Not equal in either value or type (x!=="9") is true


(x!==9) is false

24
Conditional (Ternary) Operator
 JavaScript also contains a conditional operator that assigns a value to
a variable based on some condition.

 Syntax: variablename = (condition) ? value1:value2

 Ex:
var age= 10;

var voteable = (age < 18) ? "Too young":"Old enough";

The result of voteable will be: Too young

25
Logical Operators
 The Boolean operators AND, OR, and NOT are represented with &&
(and), || (or), and ! (not).

AND Truth Table OR Truth Table NOT Truth Table

 Ex: Given that x = 6 and y = 3,

Operator Example
&& (x < 10 && y > 1) is true
|| (x == 5 || y == 5) is false
! !(x == y) is true

26
Conditionals
If, else if, …, else

 The condition to test is contained within ( ) brackets with the body


contained in { } blocks.

 Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
// condition2 is true
} else {
// block of code to be executed if the condition1 is false and
// condition2 is false
}

27
Conditionals
If, else if, …, else

 Ex:

var hourOfDay=9; // var to hold hour of day.


var greeting; // var to hold the greeting message.

if (hourOfDay > 4 && hourOfDay < 12) { // if statement with condition


greeting = "Good Morning";
}
else if (hourOfDay >= 12 && hourOfDay < 20) { // optional else if
greeting = "Good Afternoon";
}
Else { // optional else branch
greeting = "Good Evening";
}

28
Conditionals
switch

 The switch statement is used to perform different actions based on


different conditions.

 Syntax: switch(expression) {
case x:
// code block • When JavaScript reaches a break keyword, it
break; breaks out of the switch block. This will stop
case y: the execution of inside the block.
// code block
break; • The default keyword specifies the code to run
default: if there is no case match.
// code block
}

 It works as follows:
 The switch expression is evaluated once.
 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.

29
Conditionals
switch

 Ex: var day=" ";


switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday"; }

30
Loops
Round and round we go

 JavaScript supports different kinds of loops:


 for - loops through a block of code a number of times
 for/in - loops through the properties of an object
 for/of - loops through the values of an iterable object
 while - loops through a block of code while a specified condition is true
 do/while - also loops through a block of code while a specified condition
is true

 Like conditionals, loops use the ( ) and { } blocks to define the


condition and the body of the loop.

31
For Loop
 Syntax:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}

 A for loop combines the common components of a loop: initialization,


condition, and post-loop operation into one statement.

 This statement begins with the for keyword and has the components
placed between ( ) brackets, semicolon (;) separated as shown.

 Ex: var text=" ";


var i;

for (i = 0; i < 5; i++) {


text += "The number is " + i + "<br>";
}

32
For/in Loop
 It is used to enumerate the non-symbol keyed properties of an object.

 Syntax:
for (property in expression) {
statement
}

 Ex: for (var propName in window) {


document.write(propName);
}

 Note: the for-in statement simply doesn’t execute the body of the
loop if the variable representing the object to iterate over is null or
undefined.

33
For/of Loop
 It is used to loop through elements in an iterable object.

 Syntax: for (property of expression) {


statement
}

 Example:
for (var el of [2,4,6,8]) {
document.write(el); // 2 4 6 8
}
for (var el in [2,4,6,8]) {
document.write(el); // 0 1 2 3
}
 Note: the for-of statement will throw an error if the entity that it is
attempting to iterate over does not support iteration.

34
While Loops
 Syntax:
while (condition) {
// code block to be executed
}

 While loops normally initialize a loop control variable before the loop,
use it in the condition, and modify it within the loop.

 Ex: var text=" ";


var i=1;

while (i < 10) {


text += "The number is " + i;
i++;
}

35
Do/While Loop
 Syntax:
do {
// code block to be executed
}
while (condition);

 The loop will always be executed at least once, even if the condition is
false, because the code block is executed before the condition is
tested.

 Ex: var text=" ";


var i=1;
do {
text += "The number is " + i;
i++;
}
while (i < 10);

36
Functions
 A JavaScript function is a block of code designed to perform
a particular task.

 A JavaScript function is executed when "something" invokes it.

 Functions are the building block for modular code in JavaScript, and
are even used to build pseudo-classes.

 They are defined by using the reserved word function and then the
function name and (optional) parameters.

 Syntax: function name(parameter1, parameter2, parameter3) {


// code to be executed
}
 Since JavaScript is dynamically typed, functions do not require
a return type, nor do the parameters require type.

37
Functions
 Ex:
function myFunction(p1, p2) {
return p1 * p2; // The function returns the product of p1 and p2
}
called as: var x = myFunction(4, 3);
 Ex:
function power(x, y) {
var pow=1;
for (var i=0; i<y; i++) {
pow = pow*x;
}
return pow;
}
called as: var x =power(2, 3);

38
Javascript Popup Boxes
 JavaScript has three kind of popup boxes: Alert box, Confirm box, and
Prompt box.

 Alert Box
 It is often used if you want to make sure information
comes through to the user.
 When an alert box pops up, the user will have to click
"OK" to proceed.
 Syntax: window.alert("sometext"); or alert("sometext");

 Confirm Box
 It 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. If the user clicks
"Cancel", the box returns false.
 Syntax: window.confirm("sometext"); or confirm("sometext");

39
Javascript Popup Boxes
 Prompt Box
 It is often used if you want the user to input a value before entering a page.
 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. If the user
clicks "Cancel" the box returns null.
 Syntax: window.prompt("sometext","defaultText");
or prompt("sometext","defaultText");

40
Errors using try and catch
 When the browser’s JavaScript engine encounters an error, it will
throw an exception.

 Errors can be coding errors made by the programmer, errors due to


wrong input, and other unforeseeable things.

 These exceptions interrupt the regular, sequential execution of the


program and can stop the JavaScript engine altogether.

 You can optionally catch these errors preventing disruption of the


program using the try–catch block
try {
tryCode - Block of code to try
}
catch(err) {
catchCode - Block of code to handle errors
}

41
Errors using try and catch
 The try/catch statement handles some or all of the errors that may
occur in a block of code, while still running code.

 The try statement allows you to define a block of code to be tested for
errors while it is being executed.

 The catch statement allows you to define a block of code to be


executed, if an error occurs in the try block.

 Ex:
try {
nonexistantfunction("hello");
}
catch(err) {
alert("An exception was caught:" + err);
}

42
Comments
 There are two styles of comment in JavaScript:
 The end-of-line comment, which starts with two slashes //.

 The block comment, which begins with /* and ends with */.

 Ex:
var x = 5; // I will be executed

// var x = 6; I will NOT be executed

43
JavaScript Output
 JavaScript can "display" data in different ways:
 Writing into the HTML output using document.write().
 Writing into an HTML element, using innerHTML.
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().

 Using document.write():
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>

44
JavaScript Output
 Using innerHTML:
 To access an HTML element, JavaScript can use the document.getElementById(id)
method.
 The id attribute defines the HTML element. The innerHTML property defines the
HTML content:

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>

45
JavaScript Output
 Using window.alert():
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html> <!DOCTYPE html>
<html>
 Using console.log(): <body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
console.log(5 + 6);
</script>
</body>
</html>

46
Web Programming

JavaScript: Client-Side Scripting


-2-

Dr. Mohammed Alborihi


Objectives

1 JavaScript Objects

2 The DOM

2
Section 1 of 2

JAVASCRIPT OBJECTS
Javascript Objects
 ECMA-262 defines an object as an unordered collection of properties.
Each property or method is identified by a name that is mapped to
a value.

 The canonical way of creating a custom object is to create a new instance


of Object and add properties and methods to it.
var person = new Object();
person.name = "Nicholas";
person.age = 29;
person.job = "Software Engineer";
person.sayName = function() {
return this.name;
};

 Object literals became the preferred pattern for creating such objects.
var person = { name: "Nicholas",
age: 29,
job: "Software Engineer",
sayName: function() { return this.name; }
};

4
Object Properties
 The name:values pairs in JavaScript objects are called properties.

 You can access object properties in two ways: dot notation or


bracket notation.
 objectName.propertyName. Ex: person.name;
 objectName["propertyName"]. Ex: person["name"];

 Bracket notation allows you to use variables for property access, and
to use property names that contains characters that would be either
a syntax error or a keyword/reserved word.
var propertyName = "name";
person[propertyName]="Nicholas";
console.log(person[propertyName]); // "Nicholas"
person["first name"] = "Nicholas";

5
Object Properties
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
id : 5566
};
// Display some data from the object:
document.getElementById("demo").innerHTML = person.firstName + " " +
person.lastName;
</script>

</body>
</html>

6
Object Methods
 Objects can also have methods.

 Methods are actions that can be performed on objects.

 Methods are stored in properties as function definitions.


var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

 You access an object method with the following syntax:


objectName.methodName();. Ex: name = person.fullName();

7
Object Methods
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// Display some data from the object:
document.getElementById("demo").innerHTML = person.fullName();
</script>

</body>
</html>

8
Object Creation
 Although using the Object constructor or an object literal are convenient
ways to create single objects, there is an downside: Creating multiple
objects with the same interface requires a lot of code duplication.

 The Factory Pattern


 The factory pattern is used to abstract away the process of creating objects.
function createPerson(name, age, job) {
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function() {
console.log(this.name);
};
return o;
}
var person1 = createPerson("Nicholas", 29, "Software Engineer");
var person2 = createPerson("Greg", 27, "Doctor");
 Though this solved the problem of creating multiple similar objects, the
factory pattern didn’t address the issue of object identification.
9
Object Creation
 The Function Constructor Pattern
 Constructors in ECMAScript are used to create specific types of objects.
 There are native constructors, such as Object and Array.
 It is also possible to define custom constructors, in the form of a function
that define properties and methods for our own type of object.
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function() {
console.log(this.name);
};
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
person1.sayName(); // Nicholas
person2.sayName(); // Greg
 The major downside to constructors is that methods are created once for
each instance. functions are objects in ECMAScript, so every time
a function is defined, it’s actually an object being instantiated.
10
Object Creation
 It doesn’t make sense to have two instances of Function that do the same
thing. It’s possible to work around this limitation by moving the function
definition outside of the constructor, as follows:
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = sayName;
}
function sayName() { console.log(this.name); }
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
person1.sayName(); // Nicholas
person2.sayName(); // Greg
 This solves the problem of having duplicate functions that do the same thing
but also creates some clutter in the global scope by introducing a function
that can realistically be used only in relation to an object.
 If the object needed multiple methods, that would mean multiple global
functions, and all of a sudden the custom reference type definition is no
longer nicely grouped in the code.
11
Object Creation
 The Prototype Pattern
 Each function is created with a prototype property, which is an object containing
properties and methods that should be available to instances of a particular
object.
 The benefit of using the prototype is that all of its properties and methods are
shared among object instances.
 Instead of assigning object information in the constructor, they can be assigned
directly to the prototype.
function Person() {}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function() {
console.log(this.name);
};
var person1 = new Person();
person1.sayName(); // "Nicholas"
var person2 = new Person();
person2.sayName(); // "Nicholas"
console.log(person1.sayName == person2.sayName); // true

12
Object Creation
 The Prototype Hierarchy
 Whenever a property is accessed for reading on an object, a search is started to
find a property with that name. The search begins on the object instance itself.
 If a property with the given name is found on the instance, then that value is returned.
 If the property is not found, then the search continues up the pointer to the prototype. If
the property is found on the prototype, then that value is returned.
 If you add a property to an instance that has the same name as a property on the
prototype, you create the property on the instance, which then masks the property
on the prototype.
function Person() {}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function() {
console.log(this.name);
};
var person1 = new Person();
var person2 = new Person();
person1.name = "Greg";
console.log(person1.name); // "Greg" - from instance
console.log(person2.name); // "Nicholas" - from prototype

13
Objects Included in JavaScript
 In JavaScript, almost "everything" is an object.
 Booleans can be objects (if defined with the new keyword)
 Numbers can be objects (if defined with the new keyword)
 Strings can be objects (if defined with the new keyword)
 Dates are always objects
 Maths are always objects
 Arrays are always objects
 Dom objects

14
Boolean
 A JavaScript Boolean represents one of two values: true or false.

 Normally JavaScript booleans are primitive values created from


literals, But booleans can also be defined as objects with the
keyword new.
var x = false; // literal
var y = new Boolean(false);

// typeof x returns boolean


// typeof y returns object

 Note: You can use the JavaScript typeof operator to find the type of
a JavaScript variable.

15
Boolean Methods
 You can use the Boolean() function to find out if an expression (or
a variable) is true.
Boolean(10 > 9) // returns true

 Everything With a "Value" is True.


var b1 = Boolean(100); // returns true
var b2 = Boolean(3.14); // returns true
var b3 = Boolean(-15); // returns true
var b4 = Boolean("Hello"); // returns true
 Everything Without a "Value" is False.
var x = 0; Boolean(x); // returns false
var x = ""; Boolean(x); // returns false
var x; Boolean(x); // returns false
var x = null; Boolean(x); // returns false
var x = false; Boolean(x); // returns false

16
Number
 JavaScript does not define different types of numbers, like integers,
short, long, floating-point etc.

 JavaScript has only one type of number. Numbers can be written


with or without decimals.
var x = 3.14; // A number with decimals
var y = 3; // A number without decimals

 Normally JavaScript numbers are primitive values created from


literals, But numbers can also be defined as objects with the
keyword new.
var x = 123; // literal
var y = new Number(123);

// typeof x returns number


// typeof y returns object

17
Number Properties and Methods
 toString() method returns a number as a string. All number methods
can be used on any type of numbers (literals, variables, or expressions).
var x = 123;
x.toString(); // returns 123 from variable x
(123).toString(); // returns 123 from literal 123
(100 + 23).toString(); // returns 123 from expression 100 + 23

 Number() method can be used to convert JavaScript variables to


numbers
Number(true); // returns 1
Number(false); // returns 0
Number("10"); // returns 10
Number(" 10"); // returns 10
Number("10 "); // returns 10
Number(" 10 "); // returns 10
Number("10.33"); // returns 10.33
Number("10,33"); // returns NaN
Number("10 33"); // returns NaN
Number("John"); // returns NaN

18
Number Properties and Methods
 parseInt() method parses a string and returns a whole number.
Spaces are allowed. Only the first number is returned.
parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("10 20 30"); // returns 10
parseInt("10 years"); // returns 10
parseInt("years 10"); // returns NaN

 parseFloat() method parses a string and returns a number. Spaces


are allowed. Only the first number is returned
parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("10 20 30"); // returns 10
parseFloat("10 years"); // returns 10
parseFloat("years 10"); // returns NaN

19
Number Properties and Methods
 MAX_VALUE property returns the largest possible number in
JavaScript.

 MIN_VALUE property returns the lowest possible number in


JavaScript.

 NaN is a JavaScript reserved word indicating that a number is not a


legal number.
var x = Number.MAX_VALUE; // x will return 1.7976931348623157e+308
var x = Number.MIN_VALUE; // x will return 5e-324
var x = 100 / "Apple"; // x will be NaN (Not a Number)

20
String
 JavaScript strings are used for storing and manipulating text.

 A JavaScript string stores a series of characters like "John Doe".

 A string can be any text inside double or single quotes:


var carName1 = "Volvo XC60";
var carName2 = 'Volvo XC60';

 Because strings must be written within quotes, JavaScript will


misunderstand this string:
var x = "We are the so-called "Vikings" from the north.";

 The solution to avoid this problem, is to use the backslash escape


character.
var x = "We are the so-called \"Vikings\" from the north.";

21
:

String
Code Result Description
\' ' Single quote
\" " Double quote
\\ \ Backslash

 Normally, JavaScript strings are primitive values, created from literals,


But strings can also be defined as objects with the keyword new.
var x = "John"; // literal
var y = new String("John");

// typeof x will return string


// typeof y will return object

22
String Properties and Methods
 The length property returns the length of a string.
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
The result: sln= 26

 indexOf() method returns the index or position of the first occurrence of


a specified text in a string (or –1 if the text isn’t found). This method begins
looking for the text at the beginning of string and accepts an optional second
argument that indicates the position to start searching from within the string.
var str = "Please locate where 'locate' occurs!";
var pos1 = str.indexOf("locate");
var pos2 = str.indexOf("locate", 15);
The result: pos1= 7, pos2=21

 lastIndexOf() method returns the index of the last occurrence of a specified


text in a string. This method var str = "Please locate where 'locate' occurs!";
begins looking from the end var pos1 = str.lastIndexOf("locate");
var pos2 = str.lastIndexOf("locate", 15);
of string. The result: pos1= 21, pos2=7

23
String Properties and Methods
 search() method accepts a single argument, which is either a regular-
expression string or a RegExp object, and returns the index of the first
pattern occurrence in the string or –1 if it’s not found.
var text = "cat, bat, sat, fat";
var pos = text.search(/at/);
console.log(pos);
The result: pos= 1

 replace() method accepts two arguments. The first argument can be


a RegExp object or string, the second argument can be a string or a function.
str = "Please visit Microsoft! and Microsoft!";
var n1 = str.replace("Microsoft", "W3Schools");
var n2 = str.replace(/Microsoft/g, "W3Schools");
The result: n1= "Please visit W3Schools! and Microsoft!"
n2= "Please visit W3Schools! and W3Schools!"

24
String Properties and Methods
 slice(), substr(), and substring() methods return a substring of the string
they act on, and all accept either one or two arguments. The first argument
is the position where capture of the substring begins; the second argument,
if used, indicates where the operation should stop:
 For slice() and substring(), the second argument is the position before which
capture is stopped.
 For substr(), the second argument is the number of characters to return.
 If the second argument is omitted in any case, it is assumed that the ending
position is the length of the string.
 There are different behaviours for these methods when an argument is
a negative number:
 For the slice() method, a negative argument is treated as the length of the string
plus the negative argument.
 For the substr() method, a negative first argument is treated as the length of the
string plus the number, whereas a negative second number is converted to 0.
 For the substring() method, all negative numbers are converted to 0.

25
String Properties and Methods
 Ex: var stringValue = "hello world";
var res1=stringValue.slice(3);
var res2=stringValue.substring(3);
var res3= stringValue.substr(3);
var res4=stringValue.slice(3, 7);
var res5 = stringValue.substring(3, 7);
var res6= stringValue.substr(3, 7);
The result: res1= "lo world" res2= "lo world"
res3= "lo world" res4= "lo w"
res5= "lo w" res6= "lo worl"

 Ex: var stringValue = "hello world";


var res1=stringValue.slice(-3);
var res2=stringValue.substring(-3);
var res3= stringValue.substr(-3);
var res4=stringValue.slice(3, -4);
var res5 = stringValue.substring(3, -4);
var res6= stringValue.substr(3, -4);
The result: res1= "rld" res2= "hello world"
res3= "rld" res4= "lo w"
res5= "hel" res6= ""

26
String Properties and Methods
 toUpperCase() method converts string to upper case. While toLowerCase()
method converts string to lower case.
var text1 = "Hello World!"; // String
var text2 = text1.toUpperCase(); // text2 is text1 converted to upper
var text3 = text1.toLowerCase(); // text3 is text1 converted to lower
The result: text2= "HELLO WORLD!"
text3= "hello world!"

 concat() method joins two or more strings.


var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2);
var text4 = "Hello" + " " + "World!";
The result: text3= "Hello World!"
text4= "Hello World!"

 trim() method removes whitespace from both sides of a string.


var str1 = " Hello World! ";
var str2= str1.trim();
The result: str2= "Hello World!"

27
String Properties and Methods
 charAt() method returns the character at a specified index in a string.
var str = "HELLO WORLD";
var c= str.charAt(0);
The result: c="H"

 split() method separates the string into an array of substrings based on


a separator.
var txt = "a,b,c,d,e"; // String
txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe
var txt = "Hello"; // String
var arr= txt.split(""); // Split in characters

The result: arr = ["H", "e", "l", "l", "o"]

var txt = "How are you doing today?"; // String


var arr= txt.split(" "); // Split in spaces
The result: arr = ["How" , "are" , "you" , "doing" , "today?"]

28
Date Object
 The Date object is used to work with dates and times.
 Date objects are created with new Date().
 There are four ways of instantiating a date:
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

 Ex:
var d = new Date(); // creates a new date object with the current date and time

var d = new Date(100000000000); // Sat Mar 03 1973 11:46:40 GMT+0200

var d = new Date("October 13, 2014 11:13:00"); // Mon Oct 13 2014 11:13:00 GMT+0300

var d = new Date(2019, 11, 24, 10, 33, 30, 0); // Tue Dec 24 2019 10:33:30 GMT+0200

29
Date Object methods
 getDate() method returns the day of the month (from 1 to 31) for the
specified date.

 getDay() method returns the day of the week (from 0 to 6) for the
specified date.

 getMonth() method returns the month (from 0 to 11) for the specified
date, according to local time.

 getFullYear() method returns the year (four digits for dates between
1000 and 9999) of the specified date.
 getHours() method returns the hour (from 0 to 23) of the specified
date and time.

 getMinutes() method returns the minutes (from 0 to 59) of the


specified date and time.

30
Date Object methods
 getSeconds() method returns the seconds (from 0 to 59) of the
specified date and time.

 getMilliseconds() method returns the milliseconds (from 0 to 999) of


the specified date and time.

 getTime() method returns the number of milliseconds between


midnight of January 1, 1970 and the specified date.

 Date.now() method returns the number of milliseconds since January


1, 1970 00:00:00 UTC.

 toString() method converts a Date object to a string.

31
Date Object methods
 Ex:
var d = new Date("July 21, 1983 01:15:00");

var n = d.getDate(); // returns 21


var n = d.getDay(); // returns 4
var n = d.getMonth(); // returns 6
var n = d.getFullYear(); // returns 1983
var n = d.getHours(); // returns 1
var n = d.getMinutes(); // returns 15
var n = d.getSeconds(); // returns 0
var n = d.getMilliseconds(); // returns 0
var n = d.getTime(); // returns 427587300000

var n = Date.now(); // returns 1565551246841

32
Math Object
 The JavaScript Math object allows you to perform mathematical tasks
on numbers.

 Math.round(x) returns the value of x rounded to its nearest integer.


Math.round(4.7); // returns 5
Math.round(4.4); // returns 4

 Math.pow(x, y) returns the value of x to the power of y.


Math.pow(8, 2); // returns 64

 Math.sqrt(x) returns the square root of x.


Math.sqrt(64); // returns 8

 Math.abs(x) returns the absolute (positive) value of x.


Math.abs(-4.7); // returns 4.7

33
Math Object
 Math.ceil(x) returns the value of x rounded up to its nearest integer.
Math.ceil(4.4); // returns 5

 Math.floor(x) returns the value of x rounded down to its nearest


integer.
Math.floor(4.7); // returns 4

 Math.sin(x) returns the sine (a value between -1 and 1) of the angle x


(given in radians).
Math.sin(90 * Math.PI / 180); // returns 1 (the sine of 90 degrees)

 Math.cos(x) returns the cosine (a value between -1 and 1) of the angle


x (given in radians).
Math.cos(0 * Math.PI / 180); // returns 1 (the cos of 0 degrees)

34
Math Object
 Math.min() and Math.max() can be used to find the lowest or highest
value in a list of arguments.
Math.min(0, 150, 30, 20, -8, -200); // returns -200
Math.max(0, 150, 30, 20, -8, -200); // returns 150

 Math.random() returns a random number between 0 (inclusive), and 1


(exclusive). Math.random(); // returns a random number

 JavaScript provides 8 mathematical constants that can be accessed with


the Math object.
Math.E // returns Euler's number: 2.718281828459045
Math.PI // returns PI: 3.141592653589793
Math.SQRT2 // returns the square root of 2: 1.4142135623730951
Math.SQRT1_2 // returns the square root of 1/2: 0.7071067811865476
Math.LN2 // returns the natural logarithm of 2: 0.6931471805599453
Math.LN10 // returns the natural logarithm of 10: 2.302585092994046
Math.LOG2E // returns base 2 logarithm of E: 1.4426950408889634
Math.LOG10E // returns base 10 logarithm of E : 0.4342944819032518

35
Array Object
 As in other languages, Javascript arrays are ordered lists of data, but
unlike in other languages, they can hold any type of data in each slot.

 We can create an array using:


 an array literal:
var cars = ["Saab", "Volvo", "BMW"];
 The JavaScript Keyword new:
var cars = new Array("Saab", "Volvo", "BMW");

 You access an array element by referring to the index number.


var name = cars[0]; // returns Saab

 You can change the value of an element in array as follows:


cars[0] = "Opel";

36
Array Properties and Methods
 length property of an array returns the length of an array (the number
of array elements).
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is 4

fruits = ["Banana", "Orange", "Apple", "Mango"];


var last = fruits[fruits.length - 1]; // Accessing the Last Array Element

 forEach() method Runs the given function on every item in the array.
This method has no return value. var fruits, text;
fruits = ["Banana", "Orange", "Apple", "Mango"];
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
text = "<ul>";
fLen = fruits.length;
// looping array elements
fruits.forEach(myFunction);
text = "<ul>";
text += "</ul>";
// looping array elements
for (i = 0; i < fLen; i++) {
function myFunction(value) {
text += "<li>" + fruits[i] + "</li>";
text += "<li>" + value + "</li>";
}
}
text += "</ul>";

37
Array Properties and Methods
 push() method adds a new element to an array (at the end) and
returns the array’s new length.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x=fruits.push("Lemon"); // adds a new element (Lemon) to fruits
and the value of x is 5

 pop() method removes the last element of an array, and returns that
element.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var f= fruits.pop(); // removes the element (Mango) from fruits and returns it
so the value of f is Mango

 shift() method removes the first item of an array, and returns that
element. unshift() method adds a new element to an array (at the
beginning) and returns the new array length.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var f= fruits.shift(); // removes the element (Banana) from fruits and returns it
so the value of f is Banana
38
Array Properties and Methods
 concat() method is used to join two or more arrays.
var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = hege.concat(stale);
The result: ["Cecilie", "Lone", "Emil", "Tobias", "Linus"]

 sort() method sorts the items of an array. By default, the sort() method
sorts the values as strings in alphabetical and ascending order.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
The result: ["Apple", "Banana", "Mango", "Orange"]

 reverse() method reverses the order of the elements in an array.


var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.reverse();
The result: ["Mango", "Apple", "Orange", "Banana"]

39
Section 2 of 2

DOCUMENT OBJECT MODEL (DOM)


The DOM
Document Object Model

 JavaScript is almost always used to interact with the HTML document


in which it is contained.

 This is accomplished through a programming interface (API) called the


Document Object Model.

 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, with the


root, or topmost object called the Document Root.

 The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.

41
DOM Example

42
DOM Nodes
 In the DOM, each element within the HTML document is called a node. If
the DOM is a tree, then each node is an individual branch.

 There are:
 Element nodes

 Text nodes

 Attribute nodes

 Comment nodes

 All nodes in the DOM share a common set of properties and methods.

43
DOM Nodes
Element, text and attribute nodes

<p>Photo of Conservatory Pond in


<a href="http://www.centralpark.com/">Central Park</a>
</p>

44
DOM Nodes
Essential Node Object properties

Property Description
attributes returns a collection of the specified node's attributes, as a NamedNodeMap
object
childNodes Returns a collection of an element's child nodes (including text and
comment nodes) as a NodeList object.
firstChild returns the first child node of the specified node, as a Node object
lastChild returns the last child node of the specified node, as a Node object
nextSibling returns the node immediately following the specified node, in the same tree
level, as a Node object
nodeName Returns the name of a node
nodeType Returns the node type of a node
nodeValue Sets or returns the value of a node
parentNode returns the parent node of the specified node, as a Node object.
previousSibling returns the previous node of the specified node, in the same tree level, as
a Node object.

45
Example1

<body>
<img id="myImg" alt="Flower" src="klematis.jpg" width="150" height="113">
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction() {
var x = document.getElementById("myImg");
var txt = "";
var i;
for (i = 0; i < x.attributes.length; i++) {
txt = txt + x.attributes[i].name + " = " + x.attributes[i].value + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>

46
Example2

<body><!-- This is a comment node! -->


<p>Click the button get info about the body element's child nodes.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction() {
var c = document.body.childNodes;
var txt = "";
var i;
for (i = 0; i < c.length; i++) {
txt = txt + c[i].nodeName + "<br>";
}

document.getElementById("demo").innerHTML = txt;
}
</script>
</body>

47
Example3
<body>
<p id="p1">Node Object Properties Example:</p><div id="d1">the list is:</div>
<ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>
<button onclick="myFunction()">Try it</button>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>
<script>
function myFunction() {
var list1 = document.getElementById("myList").firstChild.innerHTML;
var list2 = document.getElementById("myList").lastChild.innerHTML;
var x = document.getElementById("p1").parentNode.nodeName;
var y = document.getElementById("p1").nextSibling.innerHTML;
document.getElementById("demo1").innerHTML = list1;
document.getElementById("demo2").innerHTML = list2;
document.getElementById("demo3").innerHTML = x;
document.getElementById("demo4").innerHTML = y;
}
</script>
</body>

48
Document Object
One root to ground them all

 The DOM document object is the root JavaScript object representing


the entire HTML document.

 It contains some properties and methods that we will use extensively


in our development and is globally accessible as document.
Method Description

createAttribute() Creates an attribute node

createElement() Creates an element node

createTextNode() Creates a text node

getElementById(id) Returns the element node whose id attribute matches


the passed id parameter

getElementsByTagName(name) Returns a NodeList of elements whose tag name


matches the passed name parameter

Write() Writes HTML expressions or JavaScript code to


a document

49
Accessing nodes
getElementById(), getElementsByTagName()

getElementById() method returns a single DOM element that matches the id


passed as a parameter.

getElementsByTagName() method returns an array of DOM nodes


(called a NodeList) matching the tag.

50
Example4
<head> <style> .democlass { color: red; } </style> </head>
<body>
<h1> DOM Example</h1>
<h1> Hello World</h1>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var s = document.createElement("br");
document.body.appendChild(s);
var t = document.createTextNode("this is text node");
document.body.appendChild(t);
var v = document.createElement("br");
document.body.appendChild(v);
var btn = document.createElement("button");
btn.innerHTML = "CLICK ME";
document.body.appendChild(btn);
var h1 = document.getElementsByTagName("h1")[0];
var att = document.createAttribute("class");
att.value = "democlass";
h1.setAttributeNode(att); }
</script>
</body>

51
Element node Object
 The type of object returned by the method document.getElementById()
is an Element object.

 This represents an HTML element in the hierarchy, contained between


the opening <> and closing </> tags for this element.
 can itself contain more elements

 The returned Element Node object has the node properties mentioned
earlier. It also has a variety of additional properties.
Property Description

className The current value for the class attribute of this HTML element.

id The current value for the id of this element.

innerHTML Represents all the things inside of the tags. This can be read or written to and is
the primary way which we update particular div's using JS.
style The style attribute of an element. We can read and modify this property.

tagName The tag name for the element.

52
More Properties
Some Specific HTML DOM Element Properties for Certain Tag Types

 While the previous properties are available for all HTML elements,
there are some HTML elements that have additional properties that
can be accessed.
Property Description Tags
href The href attribute used in a tags to specify a URL to link to. a

name The name property is a bookmark to identify this tag. a, input, textarea, form
Unlike id which is available to all tags, name is limited to
certain form related tags.
src Links to an external URL that should be loaded into the img, input, script
page (as opposed to href which is a link to follow when
clicked)
value The value is related to the value attribute of input tags. Input, textarea, submit
Often the value of an input field is user defined, and we
use value to get that user input.

53
Example5
<body>
<p><a id="myAnchor" href="http://www.microsoft.com">Microsoft</a></p>
<form>Name: <input type="text" id="myText" name="fname" value="Eva"></form>
<br>
<button onclick="myFunction()">Try it</button>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>

<script>
function myFunction() {
var x = document.getElementsByTagName("a")[0].id;
document.getElementById("demo1").innerHTML = x;
document.getElementById("myAnchor").href = "http://www.cnn.com/";
document.getElementById("demo2").innerHTML = "The link above now
goes to www.cnn.com.";
var y = document.getElementById("myText").name ;
document.getElementById("demo3").innerHTML = y;
}
</script>
</body>

54
Example6
<body>
<p id="p1">Hello World!</p>
<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color = "blue";
document.getElementById("p2").style.fontFamily = "Arial";
document.getElementById("p2").style.fontSize = "larger";
document.getElementById("p2").style.backgroundColor = "#FFFF00";
</script>

<p>The paragraph above was changed by a script.</p>


</body>

55
Web Programming

JavaScript: Client-Side Scripting


-3-

Dr. Mohammed Alborihi


Objectives

1 JavaScrip Events

2 Forms

2
Section 1 of 2

JAVASCRIPT EVENTS
JavaScript Events
 HTML events are "things" that happen to HTML elements like:
 When a user clicks the mouse
 When a web page has loaded
 When an image has been loaded
 When the mouse moves over an element
 When an input field is changed
 When an HTML form is submitted

 JavaScript lets you execute code when events are detected as response
to that event.

 Every HTML element contains a set of events which can trigger


JavaScript Code.

4
JavaScript Events
A brave new world

 In the original JavaScript world, events could be specified right in the


HTML markup with hooks to the JavaScript code (and still can).

 As more powerful frameworks were developed, and website design and


best practices were refined, this original mechanism was supplanted by
the listener approach.

5
Event Types
 There are several classes of event, with several types of event within
each class specified by the W3C:
 mouse events

 keyboard events

 form events

 frame events

6
Mouse events

Event Description

onclick The mouse was clicked on an element

ondblclick The mouse was double clicked on an element

onmousedown The mouse was pressed down over an element

onmouseup The mouse was released over an element

onmouseover The mouse was moved (not clicked) over an element

onmouseout The mouse was moved off of an element

onmousemove The mouse was moved while over an element

7
Keyboard events

Event Description

onkeydown The user is pressing a key (this happens first)

onkeypress The user presses a key (this happens after onkeydown)


onkeyup The user releases a key that was down (this happens last)

8
Form Events

Event Description
onblur A form element has lost focus (that is, control has moved to a different
element, perhaps due to a click or Tab key press).
onchange Some <input>, <textarea> or <select> field had their value change.
This could mean the user typed something, or selected a new choice.
onfocus Complementing the onblur event, this is triggered when an element
gets focus (the user clicks in the field or tabs to it)
onreset HTML forms have the ability to be reset. This event is triggered when
that happens.
onselect When the users selects some text. This is often used to try and prevent
copy/paste.
onsubmit When the form is submitted this event is triggered. We can do some
pre-validation when the user submits the form in JavaScript before
sending the data on to the server.

9
Frame Events
 Frame events are the events related to the browser frame that
contains your web page.

Event Description

onabort An object was stopped from loading

onerror An object or image did not properly load

onload When a document or object has been loaded

onresize The document view was resized

onscroll The document view was scrolled

onunload The document has unloaded

10
Handling Events
 HTML allows event handler attributes, with JavaScript code, to be
added to HTML elements.
 <element event='some JavaScript'> or
 <element event="some JavaScript">

 Ex:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the date.</p>
<button onclick="document.getElementById('demo').innerHTML=Date()">
The time is?</button>
<p id="demo"></p>

</body>
</html>

11
Handling Events
 JavaScript code is often several lines long. It is more common to see
event attributes calling functions.

 Ex:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the date.</p>
<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>

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

</body>
</html>

12
Example1
<!DOCTYPE html>
<html>
<body>
<p>Click "Try it" to execute the displayDate() function.</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>

<script>
document.getElementById("myBtn").onclick = displayDate;

function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>

</body>
</html>

13
Example2
<!DOCTYPE html>
<html>
<body>

<h1 onclick="changeText(this)">Click on this text!</h1>

<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>

</body>
</html>

14
Example3
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
alert("Page is loaded");
}
</script>
</head>

<body onload="myFunction()">
<h2>Hello World!</h2>

</body>
</html>

15
Example4
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</head>
<body>
Enter your name:
<input type="text" id="fname" onchange="myFunction()">
<p>When you leave the input field, a function is triggered which
transforms the input text to upper case.</p>
</body>
</html>

16
Example5
<!DOCTYPE html>
<html>
<body>
<div onmouseover="mOver(this)" onmouseout="mOut(this)"
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>

<script>
function mOver(obj) {
obj.innerHTML = "Thank You"
}
function mOut(obj) {
obj.innerHTML = "Mouse Over Me"
}
</script>

</body>
</html>

17
Example6
<!DOCTYPE html>
<html>
<body>
<div onmousedown="mDown(this)" onmouseup="mUp(this)"
style="background-color:#D94A38;width:90px;height:20px;padding:40px;">
Click Me</div>

<script>
function mDown(obj) {
obj.style.backgroundColor = "#1ec5e5";
obj.innerHTML = "Release Me";
}
function mUp(obj) {
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You";
}
</script>

</body>
</html>

18
Example7
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(x) {
x.style.background = "yellow";
}
</script>
</head>
<body>
Enter your name: <input type="text" onfocus="myFunction(this)">
<p>When the input field gets focus, a function is triggered which
changes the background-color.</p>
</body>
</html>

19
Section 2 of 2

FORMS
HTML DOM forms Collection
 The forms collection returns a collection of all <form> elements in the
document as HTMLCollection object which is an array-like list of HTML
elements..

 The elements in the collection are sorted as they appear in the source
code.

 Syntax: document.forms

 Properties
Property Description
Returns the number of <form> elements in
length
the collection.

21
HTML DOM forms Collection
 Methods
Property Description
Returns the <form> element from the collection with
the specified index (starts at 0).
[index]
Note: Returns null if the index number is out of range
Returns the <form> element from the collection with
the specified index (starts at 0).
item(index)
Note: Returns null if the index number is out of range
Returns the <form> element from the collection with
the specified id.
namedItem(id)
Note: Returns null if the id does not exist

22
Example
<!DOCTYPE html>
<html>
<body>
<form>
First Name: <input type="text" name="fname" value="Eva"><br>
Last Name: <input type="text" name="lname" value="Hriekes">
</form>
<p>Click the button to display the number of form elements in the document.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.forms.length;
document.getElementById("demo").innerHTML= " The number of Forms: " + x;
}
</script>
</body>
</html>

23
Form elements Collection
 The elements collection returns a collection of all elements in a form as
HTMLFormsControlCollection Object.

 The elements in the collection are sorted as they appear in the source
code.

 Syntax: formObject.elements

 Properties:
Property Description
Returns the number of elements in the
length
<form> element.

24
Form elements Collection
 Methods:
Property Description
Returns the element in <form> with the specified
index (starts at 0).
[index]
Note: Returns null if the index number is out of range
Returns the element in <form> with the specified
index (starts at 0).
item(index)
Note: Returns null if the index number is out of range
Returns the element in <form> with the specified id.
namedItem(id)
Note: Returns null if the id does not exist

25
Example1
<!DOCTYPE html>
<html>
<body>
<form id = "myForm" >
First Name: <input type="text" name="fname" value= "Eva"><br>
Last Name: <input type="text" name="lname" value= "Hriekes">
<input type="submit" value="Submit">
</form>
<p>Click the "Try it" button to display the number of elements in the form.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myForm").elements.length;
document.getElementById("demo").innerHTML = "Found " + x +
" elements in the form."; }
</script>
</body>
</html>

26
Example2
<!DOCTYPE html>
<html>
<body>
<form id="myForm" action="/action_page.php">
First Name: <input type="text" name="fname" value="Eva"><br>
Last Name: <input type="text" name="lname" value="Hriekes">
<input type="submit" value="Submit">
</form>
<p>Click the "Try it" button to display the value of each element in the form.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myForm");
var txt = ""; var i;
for (i = 0; i < x.length; i++) {
txt = txt + x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = txt; }
</script>
</body>
</html>

27
Validating Forms
 Form validation can be defined by many different methods:
 Server side validation is performed by a web server, after input has been
sent to the server.
 Client side validation is performed by a web browser, before input is sent
to a web server.

 Writing code to prevalidate forms on the client side will reduce the
number of incorrect submissions, thereby reducing server load.

 There are a number of common validation activities including email


validation, number validation, and data validation….etc.

 Typical validation tasks are:


 has the user filled in all required fields?
 has the user entered a valid date?
 has the user entered text in a numeric field?
 ....
28
Example1
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()“
method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>

29
Example2
<!DOCTYPE html>
<html>
<body>
<p>Please input a number between 1 and 10:</p>
<input type ="text" id="numb">
<button type="button" onclick="myFunction()">Validate</button>
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else { text = "Input OK"; }
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>

30
Example3- HTML file
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Form validation</title>
<link rel="stylesheet" href="style.css">
<script src="validator.js"></script>
</head>
<body>
<form name="contactForm" onsubmit="return validateForm()"
action="confirmation.php" method="post">
<h2>Application Form</h2>
<div class="row">
<label>Full Name</label>
<input type="text" name="name">
<div class="error" id="nameErr"></div>
</div>
<div class="row">
<label>Email Address</label>
<input type="text" name="email">
<div class="error" id="emailErr"></div>
</div>

31
Example3- HTML file
<div class="row">
<label>Mobile Number</label>
<input type="text" name="mobile" maxlength="10">
<div class="error" id="mobileErr"></div>
</div>
<div class="row">
<label>Country</label>
<select name="country">
<option>Select</option>
<option>Australia</option>
<option>India</option>
<option>United States</option>
<option>United Kingdom</option>
</select>
<div class="error" id="countryErr"></div>
</div>
<div class="row">
<label>Gender</label>
<div class="form-inline">
<label><input type="radio" name="gender" value="male"> Male</label>
<label><input type="radio" name="gender" value="female"> Female</label>
</div>
<div class="error" id="genderErr"></div>
</div>

32
Example3- HTML file
<div class="row">
<label>Hobbies <i>(Optional)</i></label>
<div class="form-inline">
<label><input type="checkbox" name="hobbies[]" value="sports"> Sports</label>
<label><input type="checkbox" name="hobbies[]" value="movies"> Movies</label>
<label><input type="checkbox" name="hobbies[]" value="music"> Music</label>
</div>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
</form>

</body>
</html>

33
Example3- CSS file(style.css)
body {
font-size: 16px;
background: #f9f9f9;
font-family: "Segoe UI", "Helvetica Neue", Arial, sans-serif;
}
h2 {
text-align: center;
text-decoration: underline;
}
form {
width: 300px;
background: #fff;
padding: 15px 40px 40px;
border: 1px solid #ccc;
margin: 50px auto 0;
border-radius: 5px;
}
label {
display: block;
margin-bottom: 5px
}

34
Example3- CSS file(style.css)
label i {
color: #999;
font-size: 80%;
}
input, select {
border: 1px solid #ccc;
padding: 10px;
display: block;
width: 100%;
box-sizing: border-box;
border-radius: 2px;
}
.row {
padding-bottom: 10px;
}
.form-inline {
border: 1px solid #ccc;
padding: 8px 10px 4px;
border-radius: 2px;
}

35
Example3- CSS file(style.css)
.form-inline label, .form-inline input {
display: inline-block;
width: auto;
padding-right: 15px;
}
.error {
color: red;
font-size: 90%;
}
input[type="submit"] {
font-size: 110%;
font-weight: 100;
background: #006dcc;
border-color: #016BC1;
box-shadow: 0 3px 0 #0165b6;
color: #fff;
margin-top: 10px;
cursor: pointer;
}
input[type="submit"]:hover {
background: #0165b6;
}

36
Example3-web page in the browser

37
Example3- javascript file(validator.js)
// Defining a function to display error message
function printError(elemId, hintMsg) {
document.getElementById(elemId).innerHTML = hintMsg;
}

// Defining a function to validate form


function validateForm() {
// Retrieving the values of form elements
var name = document.contactForm.name.value;
var email = document.contactForm.email.value;
var mobile = document.contactForm.mobile.value;
var country = document.contactForm.country.value;
var gender = document.contactForm.gender.value;
var hobbies = [];
var checkboxes = document.getElementsByName("hobbies[]");
for(var i=0; i < checkboxes.length; i++) {
if(checkboxes[i].checked) {
// Populate hobbies array with selected values
hobbies.push(checkboxes[i].value);
}
}

38
Example3- javascript file(validator.js)
// Defining error variables with a default value
var nameErr = emailErr = mobileErr = countryErr = genderErr = true;

// Validate name
if(name == "") {
printError("nameErr", "Please enter your name");
} else {
var regex = /^[a-zA-Z\s]+$/;
if(regex.test(name) === false) {
printError("nameErr", "Please enter a valid name");
} else {
printError("nameErr", "");
nameErr = false;
}
}
// Validate email address
if(email == "") {
printError("emailErr", "Please enter your email address");
} else {
// Regular expression for basic email validation
var regex = /^\S+@\S+\.\S+$/;
if(regex.test(email) === false) {
printError("emailErr", "Please enter a valid email address");

39
Example3- javascript file(validator.js)
} else {
printError("emailErr", "");
emailErr = false;
}
}
// Validate mobile number
if(mobile == "") {
printError("mobileErr", "Please enter your mobile number");
} else {
var regex = /^[1-9]\d{9}$/;
if(regex.test(mobile) === false) {
printError("mobileErr", "Please enter a valid 10 digit mobile number");
} else{
printError("mobileErr", "");
mobileErr = false;
}
}
// Validate country
if(country == "Select") {
printError("countryErr", "Please select your country");
} else {
printError("countryErr", "");
countryErr = false;
}

40
Example3- javascript file(validator.js)
// Validate gender
if(gender == "") {
printError("genderErr", "Please select your gender");
} else {
printError("genderErr", "");
genderErr = false;
}
// Prevent the form from being submitted if there are any errors
if((nameErr || emailErr || mobileErr || countryErr || genderErr) == true) {
return false;
} else {
// Creating a string from input data for preview
var dataPreview = "You've entered the following details: \n" +
"Full Name: " + name + "\n" +
"Email Address: " + email + "\n" +
"Mobile Number: " + mobile + "\n" +
"Country: " + country + "\n" +
"Gender: " + gender + "\n";
if(hobbies.length) {
dataPreview += "Hobbies: " + hobbies.join(", ");
}
// Display input data in a dialog box before submitting the form
alert(dataPreview);
} }

41
Example3-web page in the browser

42
Example3-web page in the browser

43

You might also like