Chapter 8 Javascript
Chapter 8 Javascript
1
Objectives
•Introducing JavaScript
•Working with Java Script Element
•Writing Output to the Web Page
•Working with Variables and Data
•Working with Dates
•Working with Expressions and Operators
2
Objectives
•Creating JavaScript Functions
•Working with Conditional Statements
•Working with Program Loops
•Using Arrays
•Accessing an External JavaScript File
•Commenting JavaScript Code
3
Introduction to JavaScript
• JavaScript is an interpreted programming
or script language.
• JavaScript is used in Web site date.html
development to:
automatically change a formatted date on
a Web page
cause a linked to page to appear in a
popup window
cause text or a graphic image to change
during a mouse rollover
4
Server-side and Client-side
Programs
5
Server-side and Client-side
Programs
•Server-side Programs pose problems:
must be connected to the Web server to
run the CGI script
only the programmer can create or alter
the script
the Web server’s system administrator can
place limitations on how users access the
script
the system administrator has to be
concerned about users continually accessing
the server and potentially overloading the
system
6
Server-side and Client-side
Programs
•Client-side programs :
solve many of the problems associated with
server-side scripts
computing is distributed over the Web, so that
no one server is overloaded with programming
requests
can be tested locally without first uploading it
to a Web server
are likely to be more responsive to the user
can never completely replace CGI scripts
(Server-side program) 7
The Development of JavaScript
•JavaScript is a subset of Java.
•Differences between Java and
JavaScript:
• Java is a compiled language
• JavaScript is an interpreted language
8
• A compiler is a separate program that converts the entire source program
into machine language before executing it. The machine language version
that results from compiling the procedural language is called the object
program or object code. The compiler stores the object program on storage
media for execution later. While it is compiling the source program into the
object program, the compiler checks the source program for errors. The
compiler then produces a program listing that contains the source code and
a list of any errors. This listing helps the software developer make necessary
changes to the source code and correct errors in the program. Figure 11-19
shows the process of compiling a source program.
9
The Development of JavaScript
• Comparing Java and JavaScript
The Development of JavaScript
• Jscript is a version of JavaScript supported by
Internet Explorer.
• The European Computer Manufacturers
Association (ECMA) develops scripting standards.
The standard is called ECMAScript but browsers still
generally call is JavaScript.
https://www.w3schools.com/js/js_versions.asp
11
Working with Script Element
•The Web browser runs a JavaScript
program when the Web page is first
loaded, or in response to an event.
•A JavaScript program can either be
placed directly in a Web page file or
saved in an external text file.
placing a program in an external file
allows you to hide the program code from
the user
source code placed directly in the HTML
file can be viewed by anyone.
12
Creating the Script Element
•Insert a client-side script in a Web page
using the script element.
•The syntax to embed a script is:
<script type=“mime-type”> <script type=“text/javascript”>
script commands and comments code
</script> </script>
13
Demo Webpage
Creating the Script Element
• The syntax to access an external script is:
<script src=“url” type=“mime-type”>
where url is the location of the external file containing the script.
rb_survey.html
<head>
<script src= “tny_script.js” type=“text/javascript”> </script>
</head>
You do not have to include a type attribute for JavaScript files because
browsers assume JavaScript’s MIME type, text/javascript, by default.
The script element can be used with programming languages other than
JavaScript. Other client-side scripting languages are identified by
including the MIME type of the language. For example, the scripting
language VBScript from Microsoft has the MIME type text/vbscript and
can be accessed using the following code:
<script src=“url” type=”text/vbscript”></script>
14
If you don’t want to use an external file, you can create an embedded
script by omitting the src attribute and placing all of the JavaScript
code within the script element as follows
<script type=“text/javascript”> doc_write.html
<html>
code <head>
</script> <script type="text/javascript">
function myFunction()
{
return ("Hello, have a nice day!");
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(myFunction())
</script>
<p>The script in the body section calls a function.</p>
<p>The function returns a text.</p>
</body>
</html>
15
Loading the script Element
• The script element can be placed anywhere within the HTML
document. When the browser encounters a script, it immediately
stops loading the page and begins loading script and then
processing the script commands. Only when the script is
completely processed does the browser continue to load the rest
of the HTML file.
16
• You can modify this sequence by adding the async or defer attributes to the script element.
• The async attribute tells the browser to parse/translate the HTML and JavaScript code together, only pausing to
process the script before returning to the HTML file.
• It is important to note that document objects can be referenced only after the browser has finished parsing the page content. Any
command that references a document object before the browser has parsed the HTML code will result in an error because those
objects do not yet reside in memory. To ensure that an object can be referenced within a JavaScript program, apply the defer attribute
to the script element so that JavaScript code is run only after the page is completed loaded.
17
https://www.w3schools.com/code/tryit.asp?filename=GHT1F3XS99YC
19
In this session, you will use JavaScript to write content into the web page itself. To
do that, you have to work with objects. An object is an entity within the browser or
web page that has properties that define it and methods that can be acted upon it.
For example, a video embedded on a web page is an object and has properties
such as source of the video file or the width and height of the video player. It also
has methods such as playing or pausing the video.
https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_video_js_prop
There are four kinds of JavaScript objects: built-in objects that are intrinsic to the
JavaScript language, browser objects that are part of the browser, document
objects that are part of the web document, and customized objects that are
created by the programmer for use in his or her application.
document.write(“welcome to our website”);
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_writeln
https://www.w3schools.com/code/tryit.asp?filename=GHT1F3XS99YC
Object hierarchy
• Browser objects and document objects are organized in hierarchical
structures respectively called the browser object model (BOM) and the
document object model (DOM). Figure 9-12 shows a portion of this
hierarchical structure with the window object, representing the browser
window, as the topmost object in the hierarchy
• The DOM has a hierarchy of elements with the window as the top level
object (most general object to the most specific)
Objects are items that exist in a
defined space in a Web page.
Each object is identified by an
object name.
Each object has properties that
describe its appearance, purpose,
or behavior
An object can have methods,
which are actions that can be
performed with or to it.
window.document.formName 21
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc
_writeln
23
8.3 Writing Output to the Web
Page
• JavaScript commands and names are case-sensitive. Example : -
document.write(); ≠ Document.Write();
24
Working with Variables and Data
• A variable is a named item in a program that stores
information. Example: -
variable
var year;
year = 2003;
document.write(“The year is “ + year);
Output :The year is 2003
• Note:
- The plush symbol(+) is used for text
Concatenation.
- The var is used to declare a variable in JavaScript.
25
https://www.w3schools.com/js/js_hoisting.asp
Declaring a JavaScript Hoisting
Variable
•Any of the following commands is a
legitimate way of creating a variable
named “Month”:
var Month;
Month = “December”;
OR
var Month = “December”;
27
Working with Dates
•There are two ways to create a date
object:
variable = new Date(“month, day, year, hours:minutes:seconds”)
or
variable = new Date(“month, day, year, minutes, seconds”)
• Examaple :
var Today = new Date("October 15,2003");
var Today = new Date( );
28
Retrieving the Day Value
• The Today variable has all the date and time information you need.
• JavaScript stores dates and times as the number of milliseconds since
6 p.m on 12/31/1969.
• Use built in JavaScript date methods to do calculations.
var Today = new Date("October 15,2003");
var Today = new Date( );
29
Retrieving the Day Value
•Example of getting the date from date
object:-
var Today = new Date("October 15,2003");
var Today = new Date( );
thisDate = Today.getDate()
thisMonth = Today.getMonth()+1;
thisYear = Today.getFullYear();
30
Retrieving the Year Value var Today = new Date(“April, 8,2006");
thisDate = Today.getDate()
Date Methods thisMonth = Today.getMonth()
+1;
thisYear =
Today.getFullYear();
tny_july.html
New
code
Setting Date and Time Values tny_july.html
33
Chapter 6 Working with Java Script
Working with the Math Object
• Math object: Built-in object used to perform mathematical tasks and store
mathematical values
• Syntax to apply a Math method is tny_july.html
Math.method(expression)
where method is the method applied to a mathematical expression
34
Working with Expressions and
Operators
• Expressions are JavaScript commands that assign
values to variables.
• Expressions are created using variables, values, and
operators (elements that perform actions within
the expression).
• One of the most commonly used operators is the +
operator, which performs the action of adding or
combining two elements.
35
Working with Expressions and Operators
36
Arithmetic Operators
• This figure lists some of the arithmetic operators and gives examples
of how they work.
100%5=0 102%5=2
37
https://www.w3school
Assignment Operators s.com/Js/js_operators
.asp
This figure shows additional assignment operators that
can be used. Assignment operators allow you to create
expressions that are both efficient and compact.
38
Comparison, Logical and Conditional Operators
39
Comparison, Logical and
Conditional Operators
This figure lists some of the logical operators used
by JavaScript.
40
Working with Conditional Statements
• Conditional statements are commands that run only
when specific conditions are met.
• Conditional statements require a Boolean expression.
41
Using an If Statements
•The If statement runs a set of
commands if the condition is true.
•The general syntax is:
if (condition) {
JavaScript Commands if true
}
Where condition is Boolean expression. If
condition is true, the command block is
run. If condition is false, the command
block is skipped.
42
Using an If… Else Statements
• To run the If statement for one set of commands if the condition is
true and another set of commands if the condition is false use the
If...Else statement.
• The general syntax is:
if (condition) {
JavaScript Commands if true
} else
JavaScript Commands if false
}
43
Working with Program Loops
•A program loop is a set of instructions
that is executed repeatedly.
Use program loops to configure a group
of commands to be executed a set number
of times.
The loop uses a counter to track the
number of times the command block has
been run.
44
The For Loop Exercise4_for_loop_table.html
46
The While Loop
Creating a While loop
num 1
47
The While Loop
Nesting a While loop
48
Using Arrays
• An array is an ordered collection of values referenced by a single variable
name.
var variable = new Array (size);
• The following statement shows an example of declaring an array with 2
elements.
var Cars = new Array(2);
Cars[0] = "Audi";
Cars[1] = "Mercedes";
Or
var Car = new Array(“Audi”, “Mercedes”);
49
Creating a JavaScript Function
A function is a collection of commands that performs
an action or returns a value
A function name identifies a function
Parameters are values used by the function
The function is executed only when called by another
JavaScript command
function_name(parameter values)
Demo13_Email_functions.html
50
Creating a JavaScript Function
Demo11_function_parameter Demo13_Email_functions.html
51
Creating a Function to Return a Value
For a function to return a value, it must include a return
statement
function function_name(parameters){
JavaScript commands
return value;
}
Demo11_function_parameter
52
<html>
<head>
<script type="text/javascript">
function product(a,b)
{ return a*b; }
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>
<p>The script in the body section calls a function with two parameters (4 and 3).</p>
<p>The function will return the product of these two parameters.</p>
<form name="cal" id="cal">
<table>
<tr>
<td>Number 1 :</td>
<td><input type="text" name="num1" id="num1" size="10" />
</td>
</tr>
<tr>
<td>Number 2 :</td>
<td><input type="text" name="num2" id="num2" size="10" />
</td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Multiply" onclick="document.write(product(document.getElementById('num1').value,
document.getElementById('num2').value))" /></td>
</tr>
</table>
</form>
</body>
</html>
53
ES6 allows function parameters
to have default values. • https://www.w3schools.com/js/tryit.asp?filename=
tryjs_es6_default
54
https://www.w3schools.com/js/js_arrow_function.asp
55
Accessing an External JavaScript File
The code to access an external script file is:
<script src="url" type="mime-type"></script>
Place all script elements that reference external files in the document head
<script src="rb_formsubmit2.js" defer></script>
56
Commenting Java Script Code
Comments are important programming practice.
Helps others to understand code better.
There are two types of comments:
Single Line //Single Line Comment
Multiline
/* Multiline
Comment
Example
*/
HTML comment <!-- comment -- > 57
Debugging Your JavaScript Programs
Debugging is the process of searching code to locate a
source of trouble.
There are three types of errors:
Load-time errors
Run-time errors
Logical errors
58
Debugging is the process of locating and fixing a programming error. To debug
a program, you must first determine the type of error present in your code.
59
Debugging Your JavaScript Programs
Modular code entails breaking up a program’s different
tasks into smaller, more manageable chunks
An alert dialog box is a dialog box generated by
JavaScript that displays a text message with an OK
button
alert(text);
60
Debugging Your JavaScript Programs
Microsoft offers the Microsoft Script Debugger
Firefox also provides the Firefox Error Console
Every major browser includes debugging
tools to locate and fix errors in your
JavaScript code. For most browsers, you can
open the debugging tool by pressing the F12
key on your keyboard or by selecting
Developer Tools from the browser menu
61
62
JavaScript: Form Validation
JavaScript can be used to validate input data in HTML forms
before sending off the content to a server.
JavaScript is used to provide client-side validation.
It builds into the Web page form resulting immediate
response to users.
There are common validations such as Required Fields, E-mail
Validation, etc.
Required Fields is the one that checks if a required field
has been left empty. If the required field is blank, an alert
box alerts a message and the function returns false. If a
value is entered, the function returns true (means that data
is OK):
63
Email validation – is the one that checks if the content has
the general syntax of an email.
This means that the input data must contain at least an @
sign and a dot (.). Also, the @ must not be the first
character of the email address, and the last dot must at
least be one character after the @ sign:
rb_survey.html
64
sample order form.
66
JavaScript HTML DOM Objects
JavaScript arrange objects in a Document Object Model.
The HTML DOM is a W3C standard.
DOM is an interface that permits scripts to access and update
the content, structure and style of the document.
Every element of the web page can be dynamically updated in
response to input from the user or other programs
The HTML is platform and language independent. It can be used
by any programming language like java, JavaScript and VBScript
67
Object hierarchy
The DOM has a hierarchy of elements with the window as
the top level object (most general object to the most specific)
window.document.formName 68
This figure
shows
that each
field in the
order
form has
been
given a
name.
To refer
to a
particular
field, you
attach the
field
name to
the
JavaScript
reference
for the
form.
69
JavaScript HTML DOM Objects
There is another way to reference an object and that is with an object
collection. Objects are organized into groups called object collections
An object collection is an array of all objects of a particular type, such as
all of the hyperlinks for a single document or all of the elements within a
single form.
An item from an object collection can be referenced in one of three ways:
collection[i]
collection[“name”]
collection.name
collection is the JavaScript name of the collection
i is an index number of the item in the collection
name is the name assigned to the object using the name attribute.
<img src=“tny_logo.jpg” id=”logoImg” name=“logolmg”/>
you can reference that image using any of the following expressions:
document.images[0]
document.images[“logoImg”]
document.images.logoImg 70
71
72
https://www.w3schools.com/code/tryit.asp?filename=GHT1F3XS99YC
This figure
shows
that each
field in the
order
form has
been
given a
name.
To refer
to a
particular
field, you
attach the
field
name to
the
JavaScript
reference
for the
form.
74
Document Objects
The Document object represents the entire HTML document and can be
used to access all elements in a page.
The Document object is part of the Window object and is accessed
through the window.document property.
Document Object Collections
Collection Description
anchor[ ] Returns a reference to all Anchor objects in the
document
Each object in JavaScript has properties associated with it. (properties are
object attribute)
There are several ways of working with properties.
1. the value of a property can be changed
object.property = expression
document.body.style.backgroundColor = “blue"
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_style_backgroundcolor
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_style_background
78
3. test whether the property equals a specified value in an If…Then expression
• A conditional statement changes how the Web page behaves based on the
value of an object property.
• The following JavaScript code shows how you can incorporate object
properties into a simple conditional expression:
if (document.body.style.backgroundColor =="black") {
document.body.style.color ="white";
} else {
document.body.style.color ="black";
}
• Using objects, properties, and conditional statement provides a great deal
of control over the appearance of a Web page.
79
https://www.w3schools.com/code/tryit.asp?filename=GHT1F3XS99YC
81
Document Object Properties
Property Description
body Gives direct access to the <body> element
cookie Sets or returns all cookies associated with the
current document
82
Document Object Method
Method Description
close() Closes an output stream opened with the
document.open() method, and displays the
collected data
getElementsById() Returns a reference to the first object with the
specified id
getElementsByName() Returns a collection of objects with the specified
name
getElementsByTagName() Returns a collection of objects with the specified
tagname
open() Opens a stream to collect the output from any
document.write() or document.writeln() methods
write() Writes HTML expressions or JavaScript code to a
document
writeIn() Identical to the write() method, with the addition of
writing a new line character after each expression
83
The window Object – Open new window
window.open("intro.html"); [OR]
window.open("intro.html", "_blank");
Open [intro.html] in a new tab/window
window.open("intro.html", "_self");
window.open("intro.html", "intro");
<a href="myfile.htm"
onmouseover="window.alert('Hello');">Hi</a>
88
Managing Events https://www.w3schools.com/code/tryit.asp?filename=G
HT2KJPWIBNM
<form>
<input name="colors" type="radio" onclick="document.body.style.backgroundColor ='red';"/>red <br />
• This figure shows an example of the onclick event handler used with a collection
of radio buttons.
• When the user clicks a radio button, the click event is initiated and the onclick
event handler instructs the browser to run a JavaScript command to change the
background color of the Web page.
89
90
This figure shows that events often take place in
rapid succession. https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onchang
e
Get & lose focus https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onfocus
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onblur
91 91
This figure describes event handlers that JavaScript provides.
92 92
9.5.1 Working with Event Handlers
Generally, Internet Explorer and Netscape 6.0 can
apply event handlers to most HTML tags.
Versions of Netscape prior to 6.0 apply event handlers
to a smaller number of HTML tags.
Test Web pages with a variety of browsers and
browser versions, especially if the Web page relies on
JavaScript functions to operate correctly.
93 93
https://www.w3schools.com/ta
To run a command in response to the click event, an easy way of doing this is to
create a hyperlink around the object to receive the mouse click.
The syntax for doing this is:
<a href=“javascript:JavaScript commands”>
Hypertext</a>
<!DOCTYPE html>
<html>
<body>
<a href="javascript:alert('Hello World!');">Execute JavaScript</a>
<br/>
</body>
</html>
The above code display “the Hello World” message when the hypertext
“Execute JavaScript” is clicked.
One advantage of this technique is that you can apply it to objects that might
not support the onclick event handler in all browsers or browser versions.
94
9.5.3 Using the onload Event Handler
The event handler for loading the Web page is the onload
event handler.
This handler is associated with the document object and
must be placed in the <body> tag of the HTML file.
function to run
when the page
event handler is loaded by
the browser
<body onload=“startform()”>
<table width=“620” cellpadding=“0”
cellspacing=“5”>
<tr>
95
95
This figure shows that one of the purposes of the startform() function, is to
retrieve the date string and display it in the formdate field of the order
form.
function startform(){
document.order.formdate.value=todaytxt();
}
<body onload="startform()">
<table width="620" cellpadding="0" cellspacing="5">
1 Current
date
96
This figure shows additional properties and methods that can be associated
with fields.
97
Initiating Events and JavaScript
When using JavaScript to initiate an event, you are
instructing the Web page to perform an action that a
user would normally do.
• for example, such as moving the cursor to a specific field in the form
function startform(){
2 document.order.formdate.value=todaytxt();
document.order.product.focus();
}
98 98
Creating a Calculated Field
You can use JavaScript to calculate the cost of a customer’s order based on
product purchased, quantity, sales tax, and shipping costs.
JavaScript:
• treats the values of input fields as text strings
• does not round off the values to nice digits
• displays calculated values to several digits
The dollar() function takes a value, n, and rounds it to two digits to the right of
the decimal point.
function calculate(){
var amt1, amt2, amt3, total;
3 amt1 = parseFloat(document.getElementById('Amount1').value);
amt2 = parseFloat(document.getElementById('Amount2').value);
amt3 = parseFloat(document.getElementById('Amount3').value);
total = amt1 + amt2 + amt3;
document.getElementById('totalAmount').value=total.toFixed(2); }
Parses a string and returns a floating point number Calculation 99
99
function calculate(){
var amt1, amt2, amt3, total;
amt1 = parseFloat(document.getElementById('Amount1').value);
amt2 = parseFloat(document.getElementById('Amount2').value);
amt3 = parseFloat(document.getElementById('Amount3').value);
total = amt1 + amt2 + amt3;
document.getElementById('totalAmount').value=total.toFixed(2); }
100
Working with a Selection List
JavaScript treats a selection list as an array of option values.
This figure shows the JavaScript object references and property values for
the items in a product selection list. The array of selection options starts
with an index value of 0.
10
1
Working with a Selection List
There is no value property for the selection list itself, only for the options
within the list.
The selectedIndex property indicates the index number of the selected option.
function order_price(){
item_index=document.order.product.selectedIndex; //item_index=1
item_value=document.order.product.options[item_index].value; //item_value=19.95
qty_ordered=document.order.qty.selectedIndex; //qty_ordered=10
document.order.sub1.value=dollars(item_value*qty_ordered); // 19.95*10
document.order.sub2.value=dollars(item_value*qty_ordered*0.05); //19.95*10*0.05
total_price();
}
The index number of the selected item is stored in the item_index variable.
The item_index variable is then used to determine the value of the selected
item and stores the value in the item_value variable.
The text of the selected item is stored in the item_text variable. 102
Working with a Selection List
There is no value property for the selection list itself, only for the options
within the list.
The selectedIndex property indicates the index number of the selected option.
The index number of the selected item is stored in the item_index variable.
The item_index variable is then used to determine the value of the selected
item and stores the value in the item_value variable.
The text of the selected item is stored in the item_text variable. 103
This figure shows some of the other properties and methods
associated with selection lists and selection options.
104
4
This figure shows the order_price() function.
105
9.8 Working with Radio Buttons
The JavaScript reference for a radio button is:
document.form.field[i]
• form is the name of the Web page form
• field is the name assigned to the radio button
• i is the index number of specific radio button
The first radio button has an index value of 0, the second button has an index
value of 1, and so on.
• There is no JavaScript object that refers to the entire collection of radio
buttons; You could use an If…Then statement to test which radio button was
selected.
if(document.order.shipping[0].checked)
{document.order.sub3.value="7.95";}
else if(document.order.shipping[1].checked)
{document.order.sub3.value="9.95";}
else {document.order.sub3.value="12.95";}
106
if(document.order.shipping[0].checked)
Working the { document.order.sub3.value="7.95";}
else if(document.order.shipping[1].checked)
Method
The “this” keyword is a JavaScript object name that refers to the currently
selected object.
Useful in situations where several different objects on the page might access the
same function.
• in that situation, the “this” keyword can pass along information about the
object that initiated the function 107 10
7
This figure describes some of the properties, methods, and
event handlers associated with radio buttons.
108
9.10 Working with Check Boxes
This figure lists some of the properties,
methods, and event handlers of check box
objects.
109 10
9
6 function copy_shipping(){
if(document.order.billcb.checked){
document.order.bname.value=document.order.sname.value;
document.order.bstreet.value=document.order.sstreet.value;
document.order.bcity.value=document.order.scity.value;
document.order.bstate.selectedIndex=document.order.sstate.selectedInd
ex;
document.order.bzip.value=document.order.szip.value;
}
}
<input type="checkbox" name="billcb" onclick="copy_shipping()” >
110
Controlling Form Submission
When a user completes a form and then clicks the submit
button, a submit event is initiated.
JavaScript provides the onsubmit event handler that allows
you to run a program in response to this action.
The submit event is associated with the form object, the
event handler must be placed within the <form> tag.
The onsubmit event handler must be able to override the
act of submitting the form if the form fails a validation test.
111 11
1
The syntax for doing this is:
<form onsubmit=“return function();”>
112
Submitting a Form onsubmmit return checkform.html
If a condition of the form is not met, the browser should refuse the form
submission and indicate to the user why the form was not submitted.
function checkform() {
function checkform() {
if (document.myform.age.value =="") {
if (document.myform.age.value =="") {
alert("You need to specify an age"); Ne
alert("You need to specify an age"); ede
return false;
return false; d to
br o p
} else {
} else { w s r even
return true; su b e r f t
return true; mit rom the
}
} ting
}} !
<body>
<form method="get" name="myform" onSubmit="return checkform()"
For
action="http://www.tarc.edu.my">
assignment
Age:<input type="text" name="age"/>
<input type="submit" value="Submit"/>
</form>
<script 113 11
3
• https://www.w3schools.com/js/js_validation.asp
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
</body>
</html>
114
7 <head> <script>
115
This figure shows the code to return the value
of the form_ok variable that indicates whether
or not the form was completed properly.
8
116 11
6
9.13 Creating a Dialog Box
You may want to use a dialog box to display a message to the user to indicate
that the form was not properly completed.
JavaScript supports three types of dialog boxes: alert, prompt, and confirm.
• an alert dialog box displays a message, usually alerting the user to a problem.
• the prompt dialog box displays both a message and a text box.
• the confirm dialog box display a message along withOK and Cancel buttons.
• The syntax for creating these dialog boxes is:
alert(“message”);
prompt (“message”, “default”);
confirm (“message”);
• message is the text displayed in the dialog box
• default is the default text for the prompt dialogbox
117
9 <head> <script> checkform()
if(form_ok){
alert("Your order has been submitted");}
else {
if(product_ok==false) alert("Select a product, quantity and
shipping method");
if(shipping_ok==false) alert("Enter a shipping address ");
if(payment_ok==false) alert("Enter a billing address or credit
card");
}
118
10 <body> <table>
119
Resetting a Form
When designing a form, it is important to allow the user to reset the
form.
Resetting a form does not load the page.
Use JavaScript to reload the page.
• this has the effect of resetting all field values and rerunning the
startform() function that inserts the current date.
• use the location object to reload a Web page
One of the methods associated with the location object is the
reload()method, which reloads the current page.
The syntax is simply:
location.reload();
Use JavaScript to load a different page, the command is:
location=“URL”;
• URL is the address of the Web page you want to display in the
browser
To control the reset event, use the onreset handler and apply it to the
<form> tag.
120
https://www.w3schools.com/js/js_htmldom_eventlistener.asp
•The addEventListener() method attaches an event handler to the specified element.
•The addEventListener() method attaches an event handler to an element without
overwriting existing event handlers.
•You can add many event handlers to one element.
•You can add many event handlers of the same type to one element, i.e two "click" events.
•You can add event listeners to any DOM object not only HTML elements. i.e the window
object.
•The addEventListener() method makes it easier to control how the event reacts to
bubbling.
•When using the addEventListener() method, the JavaScript is separated from the HTML
markup, for better readability and allows you to add event listeners even when you do not
control the HTML markup.
•You can easily remove an event listener by using the removeEventListener() method.
121
122
<!DOCTYPE html>
<html>
<body>
<p>Click "Try it". Wait 3 seconds, and the page will alert
"Hello".</p>
</body>
</html> 123
<!DOCTYPE html>
<!DOCTYPE html> <html>
<html> <body>
<body>
<p>Click the button to wait 3 seconds, then
<p>Click "Try it". Wait 3 seconds, and the page alert "Hello".</p>
will alert "Hello".</p>
<button onclick="myFunction()">Try
<button onclick="setTimeout(myFunction, it</button>
3000);">Try it</button>
<script>
<script> function myFunction() {
function myFunction() { setTimeout(function(){ alert("Hello"); }, 3000);
alert('Hello'); }
} </script>
</script>
</body>
</body> </html>
</html>
1000millisecond =1 second
tny_july.html 124
https://www.w3schools.com/jsref/met_win_cleartimeout.asp
125
a period between
two events or times
https://www.w3schools.com/js
ref/met_win_clearinterval.asp
126
example :count down tny_july.html
Another example
1000millisecond =1 second :Book return date
127
1000millisecond =1 second 128
End
129
ECMAScript 2009 - ES5
•ECMAScript 2009, also known as ES5, was the first major revision
to JavaScript.
•This chapter describes the most important features of ES5.
ES5 Features
•"use strict"
•String[number] access https://www.w3schools.com/js/js_
•String.trim() es5.asp
•Array.isArray()
•Array.forEach()
•Array.map()
•Array.filter()
•Array.reduce()
•Array.every()
•Array.some()
•Array.indexOf()
•Array.lastIndexOf()
•Property getters and setters
•Reserved words as property names
•Object defineProperty()
130
https://www.w3schools.com/js/js_es6.asp#mark_map
• ECMAScript 6 was the second major revision to JavaScript.
• ECMAScript 6 is also known as ES6 and ECMAScript 2015.
https://www.w3schools.com/js/js_2017.asp
New Features in ECMAScript 2017
This chapter introduces the new features in
ECMAScript 2017:
•JavaScript String padding
•JavaScript Object.entries
•JavaScript Object.values
132