You are on page 1of 30

Building Dynamic Web Pages using Java Script and VBScript 33

Notes

Unit 2: Building Dynamic Web Pages using Java


Script and VBScript

Structure:
2.1 Java Script
2.1.1 JavaScript Functions and Events
2.1.2 External JavaScript
2.1.3 External JavaScript Advantages
2.1.4 JavaScript Display Possibilities
2.2 JavaScript Programs
2.3 JavaScript Operators
2.4 Programming Statements
2.5 JavaScript Functions
2.6 Handling Events
2.7 Working with Objects
2.8 Creating Frames and Windows
2.9 Processing Forms
2.10 JavaScript Forms
2.11 Summary
2.12 Check Your Progress
2.13 Questions and Exercises
2.14 Key Terms
2.15 Check Your Progress: Answers
2.16 Case Study
2.17 Further Readings

Objectives
After going through this unit, you should be able to know:
● JavaScript
● Operators and expressions
● Programming statements
● Event handling
● Frameset and windows
● HTML
● A Case Study based on this Unit

2.1 JavaScript
JavaScript is one of the three languages all web developers must learn:

Amity Directorate of Distance and Online Education


34 Web-Enabled Business Processes
1. HTML to define the content of web pages
Notes
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages
This unit is about JavaScript, and how JavaScript works with HTML and CSS.

JavaScript
JavaScript is the programming language of HTML and the Web.
Programming makes computers do what you want them to do.
JavaScript is easy to learn.
JavaScript can be placed in the <body> and the <head> sections of an HTML page.
The <script> Tag
In HTML, JavaScript code must be inserted between <script> and </script> tags.
Example
<script>
document.getElementById(“demo”).innerHTML = “My First JavaScript”;
</script>
Older examples may use a type attribute: <script type=“text/javascript”>. The type
attribute is not required. JavaScript is the default scripting language in HTML.

2.1.1 JavaScript Functions and Events


A JavaScript function is a block of JavaScript code, that can be executed when
“asked” for.
For example, a function can be executed when an event occurs, like when the user
clicks a button.
You will learn much more about functions and events in later units.
JavaScript in <head> or <body>
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.
Keeping all code in one place, is always a good habit.
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML
page.
The function is invoked (called) when a button is clicked:
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById(“demo”).innerHTML = “Paragraph changed.”;
}
</script>
</head>

Amity Directorate of Distance and Online Education


Building Dynamic Web Pages using Java Script and VBScript 35

<body>
Notes
<h1>My Web Page</h1>
<p id=“demo”>A Paragraph</p>
<button type=“button” onclick=“myFunction()”>Try it</button>
</body>
</html>
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML
page.
The function is invoked (called) when a button is clicked:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id=“demo”>A Paragraph</p>
<button type=“button” onclick=“myFunction()”>Try it</button>
<script>
function myFunction() {
document.getElementById(“demo”).innerHTML = “Paragraph changed.”;
}
</script>
</body>
</html>
It is a good idea to place scripts at the bottom of the <body> element. This can
improve page load, because HTML display is not blocked by scripts loading.

2.1.2 External JavaScript


Scripts can also be placed in external files.
External scripts are practical when the same code is used in many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute
of the <script> tag:
Example
<!DOCTYPE html>
<html>
<body>
<script src=“myScript.js”></script>
</body>
</html>
You can place an external script reference in <head> or <body> as you like. The
script will behave as if it was located exactly where the <script> tag is located.
External scripts cannot contain <script> tags.

Amity Directorate of Distance and Online Education


36 Web-Enabled Business Processes

Notes 2.1.3 External JavaScript Advantages


Placing JavaScripts in external files has some advantages:
● It separates HTML and code.
● It makes HTML and JavaScript easier to read and maintain.
● Cached JavaScript files can speed up page loads.

2.1.4 JavaScript Display Possibilities


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

Using window.alert()
You can use an alert box to display data:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Using document.write()
For testing purposes, it is convenient to use document.write():
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using document.write() after an HTML document is fully loaded, will delete all
existing HTML:
Example
<!DOCTYPE html>

Amity Directorate of Distance and Online Education


Building Dynamic Web Pages using Java Script and VBScript 37

<html>
Notes
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button onclick=“document.write(5 + 6)”>Try it</button>
</body>
</html>
The document.write() method should be used only for testing.
Using innerHTML
To access an HTML element, JavaScript can use the document.GetElement
ById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the
HTML content:
Example
<!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>
To “display data” in HTML (in most cases), you will set the value of an innerHTML
property.
Using console.log()
In your browser, you can use the console.log() method to display data.
Activate the browser console with F12, and select “Console” in the menu.
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
console.log(5 + 6);
</script>
</body>
</html>
JavaScript syntax is the set of rules, how JavaScript programs are constructed.

Amity Directorate of Distance and Online Education


38 Web-Enabled Business Processes

Notes 2.2 JavaScript Programs


A computer program is a list of “instructions” to be “executed” by the computer.
In a programming language, these program instructions are called statements.
JavaScript is a programming language.
JavaScript statements are separated by semicolons.
Example
var x = 5;
var y = 6;
var z = x + y;
In HTML, JavaScript programs can be executed by the web browser.

JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.

JavaScript Values
The JavaScript syntax defines two types of values: fixed values and variable values.
Fixed values are called literals. Variable values are called variables.
JavaScript Literals
The most important rules for writing fixed values are:
Numbers are written with or without decimals:
10.50
1001
Strings are text, written within double or single quotes:
“John Doe”
‘John Doe’
JavaScript Variables
In a programming language, variables are used to store data values.
JavaScript uses the var keyword to define variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
var x;
x = 6;
JavaScript Operators
JavaScript uses an assignment operator (=) to assign values to variables:
var x = 5;
var y = 6;
JavaScript uses arithmetic operators (+ - * /) to compute values:
(5 + 6) * 10

Amity Directorate of Distance and Online Education


Building Dynamic Web Pages using Java Script and VBScript 39

JavaScript Expressions Notes


An expression is a combination of values, variables, and operators, which computes
to a value.
The computation is called an evaluation.
For example, 5 * 10 evaluates to 50:
5 * 10
Expressions can also contain variable values:
x * 10
The values can be of various types, such as numbers and strings.
For example, “John” + “ ” + “Doe”, evaluates to “John Doe”:
“John” + “ ” + ”Doe”
JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.
The var keyword tells the browser to create a new variable:
var x = 5 + 6;
var y = x * 10;

JavaScript Comments
Not all JavaScript statements are “executed”.
Code after double slashes // or between /* and */ is treated as a comment.
Comments are ignored, and will not be executed:
var x = 5; // I will be executed
// var x = 6; I will NOT be executed

JavaScript Identifiers
Identifiers are names.
In JavaScript, identifiers are used to name variables (and keywords, and functions,
and labels).
The rules for legal names are much the same in most programming languages.
In JavaScript, the first character must be a letter, an underscore (_), or a dollar sign ($).
Subsequent characters may be letters, digits, underscores, or dollar signs.
Numbers are not allowed as the first character. This way JavaScript can easily
distinguish identifiers from numbers.

JavaScript is Case-sensitive
All JavaScript identifiers are case-sensitive.
The variables lastName and lastname, are two different variables.
lastName = “Doe”;
lastname = “Peterson”;

2.3 JavaScript Operators


Example
Assign values to variables and add them together:

Amity Directorate of Distance and Online Education


40 Web-Enabled Business Processes
var x = 5; // assign the value 5 to x
Notes
var y = 2; // assign the value 2 to y
var z = x + y; // assign the value 7 to z (x + y)
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic on numbers (literals or variables).
Operator Description
+ Addition
– Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
–– Decrement
The addition operator (+) adds numbers:
Adding
var x = 5;
var y = 2;
var z = x + y;
The multiplication operator (*) multiplies numbers.
Multiplying
var x = 5;
var y = 2;
var z = x * y;
You will learn more about JavaScript operators in the next units.
JavaScript 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
The assignment operator (=) assigns a value to a variable.
Assignment
var x = 10;
The addition assignment operator (+=) adds a value to a variable.
Assignment
var x = 10;
x += 5;

Amity Directorate of Distance and Online Education


Building Dynamic Web Pages using Java Script and VBScript 41

JavaScript String Operators Notes


The + operator can also be used to add (concatenate) strings.
When used on strings, the + operator is called the concatenation operator.
Example
txt1 = “John”;
txt2 = “Doe”;
txt3 = txt1 + “ ” + txt2;
The result of txt3 will be:
John Doe
The += assignment operator can also be used to add (concatenate) strings:
Example
txt1 = “What a very”;
txt1 += “nice day”;
The result of txt1 will be:
What a very nice day

Adding Strings and Numbers


Adding two numbers, will return the sum, but adding a number and a string will
return a string.
Example
x = 5 + 5;
y = “5” + 5;
z= “Hello” + 5;
The result of x, y, and z will be:
10
55
Hello5
The rule is: If you add a number and a string, the result will be a string!

JavaScript Comparison and Logical Operators


Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to

Amity Directorate of Distance and Online Education


42 Web-Enabled Business Processes

Notes 2.4 Programming Statements


In HTML, JavaScript statements are “instructions” to be “executed” by the web
browser.

JavaScript Statements
This statement tells the browser to write “Hello Dolly.” inside an HTML element with
id = “demo”.
Example
document.getElementById(“demo”).innerHTML = “Hello Dolly.”;

JavaScript Programs
Most JavaScript programs contain many JavaScript statements.
The statements are executed, one by one, in the same order as they are written.
In this example, x, y, and z is given values, and finally z is displayed:
Example
var x = 5;
var y = 6;
var z = x + y;
document.getElementById(“demo”).innerHTML = z;
JavaScript programs (and JavaScript statements) are often called JavaScript code.
Semicolons;
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:
a = 5;
b = 6;
c = a + b;
When separated by semicolons, multiple statements on one line are allowed:
a = 5; b = 6; c = a + b;
On the web, you might see examples without semicolons.
Ending statements with semicolon is not required, but highly recommended.
JavaScript White Space
JavaScript ignores multiple spaces. You can add white space to your script to make
it more readable.
The following lines are equivalent:
var person = “Hege”;
var person=“Hege”;
A good practice is to put spaces around operators (= + - * /):
var x = y + z;
JavaScript Line Length and Line Breaks
For best readability, programmers often like to avoid code lines longer than
80 characters.

Amity Directorate of Distance and Online Education


Building Dynamic Web Pages using Java Script and VBScript 43

If a JavaScript statement does not fit on one line, the best place to break it, is after
Notes
an operator.
Example
document.getElementById(“demo”).innerHTML =
“Hello Dolly.”;

JavaScript Code Blocks


JavaScript statements can be grouped together in code blocks, inside curly brackets
{...}.
The purpose of code blocks is to define statements to be executed together.
One place you will find statements grouped together in blocks, are in JavaScript
functions:
Example
function myFunction() {
document.getElementById(“demo”).innerHTML = “Hello Dolly.”;
document.getElementById(“myDIV”).innerHTML = “How are you?”;
}
JavaScript keywords are reserved words. Reserved words cannot be used as
names for variables.
In this unit, we use four spaces of indentation for code blocks.
You will learn more about functions later in this unit.

JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to
be performed.
Here is a list of some of the keywords you will learn about in this unit:
Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript, and calls (if available) the debugging function
do ... while Executes a block of statements, and repeats the block, while a condition is true
for Marks a block of statements to be executed, as long as a condition is true
function Declares a function
if ... else Marks a block of statements to be executed, depending on a condition
return Exits a function
switch Marks a block of statements to be executed, depending on different cases
try ... catch Implements error handling to a block of statements
var Declares a variable

2.5 JavaScript Functions


A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when “something” invokes it (calls it).

Amity Directorate of Distance and Online Education


44 Web-Enabled Business Processes
Example
Notes
function myFunction(p1, p2) {
return p1 * p2; // The function returns the product of p1 and p2
}

JavaScript Function Syntax


A JavaScript function is defined with the function keyword, followed by a name,
followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: { }
function name(parameter1, parameter2, parameter3) {
code to be executed
}
Function parameters are the names listed in the function definition.
Function arguments are the real values received by the function when it is invoked.
Inside the function, the arguments behaves as local variables.
A Function is much the same as a Procedure or a Subroutine, in other programming
languages.

Function Invocation
The code inside the function will execute when “something” invokes (calls) the
function:
● When an event occurs (when a user clicks a button)
● When it is invoked (called) from JavaScript code
● Automatically (self-invoked)

Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will “return” to execute the
code after the invoking statement.
Functions often compute a return value. The return value is “returned” back to the
“caller”.
Example
Calculate the product of two numbers, and return the result:
var x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
The result in x will be:
12

Amity Directorate of Distance and Online Education


Building Dynamic Web Pages using Java Script and VBScript 45

Why Functions?
Notes
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce
different results.
Example
Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById(“demo”).innerHTML = toCelsius(77);
The () Operator Invokes the Function
Using the example above, toCelsius refers to the function object, and toCelsius()
refers to the function result.
Example
Accessing a function without () will return the function definition:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById(“demo”).innerHTML = toCelsius;

Functions Used as Variables


In JavaScript, you can use functions the same way as you use variables.
Example
You can use:
var text = “The temperature is ” + toCelsius(77) + “ Celsius”;
Instead of:
var x = toCelsius(32);
var text = “The temperature is ” + x + “ Celsius”;

2.6 Handling Events


HTML events are “things” that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can “react” on these events.

HTML Events
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
● An HTML web page has finished loading.
● An HTML input field was changed.
● An HTML button was clicked.
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be added to HTML
elements.

Amity Directorate of Distance and Online Education


46 Web-Enabled Business Processes
With single quotes:
Notes
<some-HTML-element some-event=‘some JavaScript’>
With double quotes:
<some-HTML-element some-event=“some JavaScript”>
In the following example, an onclick attribute (with code), is added to a button element:
Example
<button onclick=‘getElementById(“demo”).innerHTML=Date()’>The time is?</button >
In the example above, the JavaScript code changes the content of the element with
id=“demo”.
In the next example, the code changes the content of its own element (using
this.innerHTML):
Example
<button onclick=“this.innerHTML=Date()”>The time is?</button>
JavaScript code is often several lines long. It is more common to see event
attributes calling functions.
Example
<button onclick=“displayDate()”>The time is?</button>

Common HTML Events


Here is a list of some common HTML events:
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page

What Can JavaScript Do?


Event handlers can be used to handle, and verify, user input, user actions, and
browser actions:
● Things that should be done every time a page loads
● Things that should be done when the page is closed
● Action that should be performed when a user clicks a button
● Content that should be verified when a user inputs data
● And more ...
Many different methods can be used to let JavaScript work with events:
● HTML event attributes can execute JavaScript code directly
● HTML event attributes can call JavaScript functions
● You can assign your own event handler functions to HTML elements
● You can prevent events from being sent or being handled
● And more ...
You will learn a lot more about events and event handlers in the HTML DOM units.

Amity Directorate of Distance and Online Education


Building Dynamic Web Pages using Java Script and VBScript 47

2.7 Working with Objects Notes

Real-life Objects, Properties, and Methods


In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:
Object Properties Methods
car.name = Fiat car.start()
car.model = 500 car.drive()
car.weight = 850kg car.brake()
car.color = white car.stop()

All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.

JavaScript Objects
You have already learned that JavaScript variables are containers for data values.
This code assigns a simple value (Fiat) to a variable named car:
var car = “Fiat”;
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
var car = {type:“Fiat”, model:500, color:“white”};
The values are written as name:value pairs (name and value separated by a colon).
JavaScript objects are containers for named values.

Object Properties
The name:values pairs (in JavaScript objects) are called properties.
var person = {firstName:“John”, lastName:“Doe”, age:50, eyeColor:“blue”};
Property Property Value
firstName John
lastName Doe
age 50
eyeColor blue

Object Methods
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.
Property Property Value
firstName John
lastName Doe
age 50

Amity Directorate of Distance and Online Education


48 Web-Enabled Business Processes

Notes eyeColor blue


fullName function() {return this.firstName + “ ” + this.lastName;}

Object Definition
You define (and create) a JavaScript object with an object literal:
Example
var person = {firstName:“John”, lastName:“Doe”, age:50, eyeColor:“blue”};
Spaces and line breaks are not important. An object definition can span multiple
lines.
Example
var person = {
firstName:“John”,
lastName:“Doe”,
age:50,
eyeColor:“blue”
};
Accessing Object Properties
You can access object properties in two ways:
objectName.propertyName
or
objectName[“propertyName”]
Example 1
person.lastName;
Example 2
person[“lastName”];

Accessing Object Methods


You access an object method with the following syntax:
objectName.methodName()
Example
name = person.fullName();
If you access the fullName property, without (), it will return the function definition:
Example
name = person.fullName;
Do Not Declare Strings, Numbers, and Booleans as Objects!
When a JavaScript variable is declared with the keyword “new”, the variable is
created as an object:
var x = new String(); // Declares x as a String object
var y = new Number(); // Declares y as a Number object
var z = new Boolean(); // Declares z as a Boolean object
Avoid String, Number, and Boolean objects. They complicate your code and slow
down execution speed.
You will learn more about objects later in this unit.

Amity Directorate of Distance and Online Education


Building Dynamic Web Pages using Java Script and VBScript 49

2.8 Creating Frames and Windows Notes


HTML <frame> Tag.
Example
A simple three-framed page:
<frameset cols=“25%,50%,25%”>
<frame src=“frame_a.htm”>
<frame src=“frame_b.htm”>
<frame src=“frame_c.htm”>
</frameset>
Definition and Usage
The <frame> tag is not supported in HTML5.
The <frame> tag defines one particular window (frame) within a <frameset>.
Each <frame> in a <frameset> can have different attributes, such as border,
scrolling, the ability to resize, etc.
Note: If you want to validate a page containing frames, be sure the <!DOCTYPE> is
set to either “HTML Frameset DTD” or “XHTML Frameset DTD”.
Browser Support
Element
<frame> Yes Yes Yes Yes Yes

Differences between HTML 4.01 and HTML5


The <frame> tag is not supported in HTML5.
Differences between HTML and XHTML
In HTML, the <frame> tag has no end tag. In XHTML, the <frame> tag must be
properly closed.
Optional Attributes
Attribute Value Description
frameborder 0 Not supported in HTML5
1 Specifies whether or not to display a border around a frame
longdesc URL Not supported in HTML5
Specifies a page that contains a long description of the content
of a frame
marginheight pixels Not supported in HTML5
Specifies the top and bottom margins of a frame
marginwidth pixels Not supported in HTML5
Specifies the left and right margins of a frame
name text Not supported in HTML5
Specifies the name of a frame
noresize noresize Not supported in HTML5
Specifies that a frame is not resizable
scrolling yes Not supported in HTML5
no Specifies whether or not to display scrollbars in a frame
auto
src URL Not supported in HTML5
Specifies the URL of the document to show in a frame

Amity Directorate of Distance and Online Education


50 Web-Enabled Business Processes

Notes 2.9 Processing Forms


HTML Forms
The <form> Element
HTML forms are used to collect user input.
The <form> element defines an HTML form:
<form>
.
form elements
.
</form>
HTML forms contain form elements.
Form elements are different types of input elements, checkboxes, radio buttons,
submit buttons, and more.
The <input> Element
The <input> element is the most important form element.
The <input> element has many variations, depending on the type attribute.
Here are the types used in this unit:
Type Description
text Defines normal text input
radio Defines radio button input (for selecting one of many choices)
submit Defines a submit button (for submitting the form)
Text Input
<input type=“text”> defines a one-line input field for text input:
Example
<form>
First name:<br>
<input type=“text” name=“firstname”>
<br>
Last name:<br>
<input type=“text” name=“lastname”>
</form>
This is how it will look like in a browser:
First name:

Last name:

Note: The form itself is not visible. Also note that the default width of a text field is
20 characters.
Radio Button Input
<input type=“radio”> defines a radio button.
Radio buttons let a user select ONE of a limited number of choices.

Amity Directorate of Distance and Online Education


Building Dynamic Web Pages using Java Script and VBScript 51

Example
Notes
<form>
<input type=“radio” name=“sex” value=“male” checked>Male
<br>
<input type=“radio” name=“sex” value=“female”>Female
</form>
This is how the HTML code above will be displayed in a browser:
Male
Female

The Submit Button


<input type=“submit”> defines a button for submitting a form to a form-handler.
The form-handler is typically a server page with a script for processing input data.
The form-handler is specified in the form’s action attribute:
Example
<form action=“action_page.php”>
First name:<br>
<input type=“text” name=“firstname” value=“Mickey”>
<br>
Last name:<br>
<input type=“text” name=“lastname” value=“Mouse”>
<br><br>
<input type=“submit” value=“Submit”>
</form>
This is how the HTML code above will be displayed in a browser:
Top of Form
First name:
Mickey

Last name:
Mouse

The Action Attribute


The action attribute defines the action to be performed when the form is submitted.
The common way to submit a form to a server, is by using a submit button.
Normally, the form is submitted to a web page on a web server.
In the example above, a server-side script is specified to handle the submitted form:
<form action=“action_page.php”>
If the action attribute is omitted, the action is set to the current page.

The Method Attribute


The method attribute specifies the HTTP method (GET or POST) to be used when
submitting the forms:

Amity Directorate of Distance and Online Education


52 Web-Enabled Business Processes
<form action=“action_page.php” method=“get”>
Notes
or:
<form action=“action_page.php” method=“post”>

When to Use GET?


You can use GET (the default method):
If the form submission is passive (like a search engine query), and without sensitive
information.
When you use GET, the form data will be visible in the page address:
action_page.php?firstname=Mickey&lastname=Mouse
GET is best suited to short amounts of data. Size limitations are set in your browser.

When to Use POST?


You should use POST:
If the form is updating data, or includes sensitive information (password).
POST offers better security because the submitted data is not visible in the page
address.

The Name Attribute


To be submitted correctly, each input field must have a name attribute.
This example will only submit the “Last name” input field:
Example
<form action=“action_page.php”>
First name:<br>
<input type=“text” value=“Mickey”>
<br>
Last name:<br>
<input type=“text” name=“lastname” value=“Mouse”>
<br><br>
<input type=“submit” value=“Submit”>
</form>

Grouping Form Data with <fieldset>


The <fieldset> element groups related data in a form.
The <legend> element defines a caption for the <fieldset> element.
Example
<form action=“action_page.php”>
<fieldset>
<legend>Personal information:</legend>
First name:<br>
<input type=“text” name=“firstname” value=“Mickey”>
<br>
Last name:<br>
<input type=“text” name=“lastname” value=“Mouse”>

Amity Directorate of Distance and Online Education


Building Dynamic Web Pages using Java Script and VBScript 53

<br><br>
Notes
<input type=“submit” value=“Submit”>
</fieldset>
</form>
This is how the HTML code above will be displayed in a browser:
Top of Form
Personal information: First name:
Mickey

Last name:
Mouse

Bottom of Form
HTML Form Attributes
An HTML <form> element, with all possible attributes set, will look like this:
<form action=“action_page.php” method=“GET” target=“_blank” accept-charset=
“UTF-8” enctype=“application/x-www-form-urlencoded” autocomplete=“off” novalidate>
.
form elements
.
</form>
Here is the list of <form> attributes:
Attribute Description
accept-charset Specifies the charset used in the submitted form (default: the page charset)
action Specifies an address (url) where to submit the form (default: the submitting
page)
autocomplete Specifies if the browser should autocomplete the form (default: on)
enctype Specifies the encoding of the submitted data (default: is URL-encoded)
method Specifies the HTTP method used when submitting the form (default: GET)
name Specifies a name used to identify the form (for DOM usage:
document.forms.name)
novalidate Specifies that the browser should not validate the form
target Specifies the target of the address in the action attribute (default: _self)

2.10 JavaScript Forms


JavaScript Form Validation
HTML form validation can be done by a JavaScript.
If a form field (fname) is empty, this function alerts a message, and returns false, to
prevent the form from being submitted:

JavaScript Example
function validateForm() {
var x = document.forms[“myForm”][“fname”].value;
if (x == null || x == “”) {
alert(“Name must be filled out”);
Amity Directorate of Distance and Online Education
54 Web-Enabled Business Processes
return false;
Notes
}
}
The function can be called when the form is submitted:

HTML Form Example


<form name=“myForm” action=“demo_form.asp” onsubmit=“return validateForm
()” method=“post”>
Name: <input type=“text” name=“fname”>
<input type=“submit” value=“Submit”>
</form>
HTML Form Validation
HTML form validation can be performed automatically by the browser:
If a form field (fname) is empty, the required attribute prevents this form from being
submitted.
HTML Form Example
<form action=“demo_form.asp” method=“post”>
<input type=“text” name=“fname” required>
<input type=“submit” value=“Submit”>
</form>
HTML form validation does not work in Internet Explorer 9 or earlier.

Data Validation
Data validation is the process of ensuring that computer input is clean, correct, and
useful.
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?
Most often, the purpose of data validation is to ensure correct input to a computer
application.
Validation can be defined by many different methods, and deployed in many
different ways.
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.
HTML Constraint Validation
HTML5 introduced a new HTML validation concept called constraint validation.
HTML constraint validation is based on:
● Constraint validation HTML Input Attributes
● Constraint validation CSS Pseudo Selectors
● Constraint validation DOM Properties and Methods

Amity Directorate of Distance and Online Education


Building Dynamic Web Pages using Java Script and VBScript 55

Constraint Validation HTML Input Attributes Notes


Attribute Description
disabled Specifies that the input element should be disabled
max Specifies the maximum value of an input element
min Specifies the minimum value of an input element
pattern Specifies the value pattern of an input element
required Specifies that the input field requires a element
type Specifies the type of an input element

Constraint Validation CSS Pseudo Selectors


Selector Description
:disabled Selects input elements with the “disabled” attribute specified
:invalid Selects input elements with invalid values
:optional Selects input elements with no “required” attribute specified
:required Selects input elements with the “required” attribute specified
:valid Selects input elements with valid values

2.11 Summary
JavaScript is a cross-platform, object-oriented scripting language. It is a small and
lightweight language. Inside a host environment (for example, a web browser),
JavaScript can be connected to the objects of its environment to provide programmatic
control over them.
JavaScript contains a standard library of objects, such as Array, Date, and Math,
and a core set of language elements such as operators, control structures, and
statements. Core JavaScript can be extended for a variety of purposes by supplementing
it with additional objects; for example:
Ɣ Client-side JavaScript extends the core language by supplying objects to
control a browser and its Document Object Model (DOM). For example,
client-side extensions allow an application to place elements on an HTML form
and respond to user events such as mouse clicks, form input, and page
navigation.
Ɣ Server-side JavaScript extends the core language by supplying objects
relevant to running JavaScript on a server. For example, server-side
extensions allow an application to communicate with a database, provide
continuity of information from one invocation to another of the application, or
perform file manipulations on a server.
JavaScript works in all modern web browsers including Firefox, Netscape,
Opera, and Internet Explorer.
2.12 Check Your Progress
I. Fill in the Blanks
1. _________ method is used to remove focus from the specified object.
2. parseFloat(“FF2”)=_________.
3. JavaScript is a __________ typed language.
4. In JavaScript, RegExp Object Method test() is used to search a string and
returns __________
5. JavaScript RegExp Object has modifier ‘i’ to __________.

Amity Directorate of Distance and Online Education


56 Web-Enabled Business Processes
II. True or False
Notes
1. Is it possible to nest functions in JavaScript?
2. In JavaScript, Window.prompt() method return true or false value.
3. In JavaScript, Window.alert() is used to allow user to enter something.
4. Are Java and JavaScript the same?
5. Is JavaScript has any date data type?
III. Multiple Choice Questions
1. Why so JavaScript and Java have similar name?
(a) JavaScript is a stripped-down version of Java
(b) JavaScript’s syntax is loosely based on Java’s
(c) They both originated on the island of Java
(d) None of the above
2. When a user views a page containing a JavaScript program, which machine
actually executes the script?
(a) The User’s machine running a Web browser
(b) The Web server
(c) A central machine deep within Netscape’s corporate offices
(d) None of the above
3. ______ JavaScript is also called client-side JavaScript.
(a) Microsoft
(b) Navigator
(c) LiveWire
(d) Native
4. _________ JavaScript is also called server-side JavaScript.
(a) Microsoft
(b) Navigator
(c) LiveWire
(d) Native
5. What are variables used for in JavaScript Programs?
(a) Storing numbers, dates, or other values
(b) Varying randomly
(c) Causing high-school algebra flashbacks
(d) None of the above
6. _________ JavaScript statements embedded in an HTML page can respond to
user events such as mouse-clicks, form input, and page navigation.
(a) Client-side
(b) Server-side
(c) Local
(d) Native
7. What should appear at the very end of your JavaScript?
The <script LANGUAGE=“JavaScript”>tag
(a) The </script>
(b) The <script>
(c) The END statement
(d) None of the above

Amity Directorate of Distance and Online Education


Building Dynamic Web Pages using Java Script and VBScript 57

8. Which of the following can’t be done with client-side JavaScript?


Notes
(a) Validating a form
(b) Sending a form’s contents by e-mail
(c) Storing the form’s contents to a database file on the server
(d) None of the above
9. Which of the following are capabilities of functions in JavaScript?
(a) Return a value
(b) Accept parameters and return a value
(c) Accept parameters
(d) None of the above
10. Which of the following is not a valid JavaScript variable name?
(a) 2names
(b) _first_and_last_names
(c) FirstAndLast
(d) None of the above

2.13 Questions and Exercises


1. What is HTML?
2. What is a tag?
3. What is the simplest HTML page?
4. How do I create frames? What is a frameset?
5. How can I include comments in HTML?
6. What is a Hypertext link?
7. How comfortable are you with writing HTML entirely by hand?
8. What is everyone using to write HTML?
9. What is a DOCTYPE? Which one do I use?
10. Can I nest tables within tables?
11. What is JavaScript?
12. Enumerate the differences between Java and JavaScript?
13. What are JavaScript types?
14. What is the use of is NaN function?
15. Between JavaScript and an ASP script, which is faster?
16. What is JavaScript?
17. What is the difference between JavaScript and JScript?
18. How do we add JavaScript onto a web page?
19. Is JavaScript case-sensitive?
20. What are the types used in JavaScript?
21. What are the Boolean operators supported by JavaScript?
22. What is the difference between “==” and “===”?
23. How to access the value of a textbox using JavaScript?
24. What are the ways of making comments in JavaScript?
25. How will you get the Checkbox status whether it is checked or not?
26. How to create arrays in JavaScript?
27. If an array with name as “names” contain three elements, then how will you
print the third element of this array?

Amity Directorate of Distance and Online Education


58 Web-Enabled Business Processes
28. How do you submit a form using JavaScript?
Notes
29. What does is NaN function do?
30. What is the use of Math Object in JavaScript?

2.14 Key Terms


Ɣ Notepad: Basic text editor you can use for simple documents or for creating
Web pages using HTML.
Ɣ Title: The text that appears on the title bar of the browser window when the
Web page appears.
Ɣ Favorites (Bookmarks): Name assigned to the page if a user adds the page
to the browser’s list of favorites.
Ɣ Body: Contains information that is displayed in the browser window.
Ɣ Background: A solid color, a picture, or a graphic against which other
elements on the Web page appear.
Ɣ Normal text: Default text format used for the main content of a Web Page.
Ɣ List: Normal text used in series of text items.
Ɣ Headings: Used to set off paragraphs of text or different sections of a page.
Ɣ Inline Image: An image used in a Web page.

2.15 Check Your Progress: Answers


I. Fill in the Blanks
1. blur()
2. NaN
3. loosely
4. true or false
5. Perform case-insensitive matching
II. True or False
1. True
2. False
3. False
4. False
5. False
III. Multiple Choice Questions
1. (b) JavaScript’s syntax is loosely based on Java’s
2. (a) The User’s machine running a Web browser
3. (b) Navigator
4. (c) LiveWire
5. (a) Storing numbers, dates, or other values
6. (a) Client-side
7. (a) The </script>
8. (c) Storing the form’s contents to a database file on the server
9. (c) Accept parameters
10. (a) 2names

Amity Directorate of Distance and Online Education


Building Dynamic Web Pages using Java Script and VBScript 59

2.16 Case Study Notes


Web Development Case Study: Upgrading Tables to Divs
It’s hard to imagine that some web developers are still using table tags for web page
layouts. But there are still some out there that do. This article will guide you through how
to upgrade a web page that uses table tags and improve it through CSS.
I was recently asked by the Principal Consultant of the firm that I work at to take a
recently developed online tool and “make it look better”. These projects are always fun,
because making it look better can mean a myriad of different things to different people. I
undertook the project with an open mind and was careful not to step on the original
developer’s toes. Here’s how it looked when I originally received it.
Looking at the code, the first thing that I noticed was that the entire page was coded
in table tags. I reworked the code so that instead of table tags, it used div tags in the CSS.
This reduced the amount of code considerably as I will discuss later in this article.
Here’s the code in tables for the row of logos along the bottom of the page, which
were ultimately moved to the top:
<table cellspacing=‘0’ cellpadding=‘0’ border=‘0’ align=‘center’ style=‘padding-top:
50px’ width=‘900’>
<tr>
<th><a href=‘http://www.fscgroup.com’ target=‘fsc’><img src=‘fsclogo.jpg’
alt=‘Freeman, Sullivan’></a></th>
<th><a href=‘http://www.lbl.gov’ target=‘bkl’><img src=‘berkeleylabslogo.jpg’
alt=‘Berkeley Labs’></a></th>
<th><a href=‘http://www.oe.energy.gov’ target=‘doe’><img src=‘doelogo.jpg’ alt=‘US
Department of Energy’></a></th>
</tr>
</table>
</th>
</tr>
</table>
I reworked the table tags into div tags. Here’s the new code for the HTML:
<div id=“logos”>
<a href=‘http://www.lbl.gov’ target=‘bkl’><img src=‘berkeleylabslogo.jpg’
alt=‘Berkeley Labs’ align=“left”></a>
<a href=‘http://www.oe.energy.gov’ target=‘doe’><img src=‘doelogo.jpg’ alt=‘US
Department of Energy’ align=“left” </a>
<a href=‘http://www.fscgroup.com’ target=‘fsc’><img src=‘fsclogo.jpg’ alt=‘Freeman,
Sullivan’ align=“right”></a>
</div>
Here’s the CSS code:
#logos {
width: 900px;
}

Amity Directorate of Distance and Online Education


60 Web-Enabled Business Processes
The amount of written code went from 447 characters to 361. That’s a difference of
Notes
86 characters, which can add up in the long run as you’ll see later in the article.
The new code for the header was designed in a similar fashion but I used nested div
tags to help with the spacing. Here is the HTML for the header that appears below the
logos in the final version:
<div id=“header”>
<a href=‘http://www.icecalculator.com/’><img src=‘powerlines.jpg’ align=“left”></a>
<div id=“text1”>
<h1 align=“left”>&nbsp;<strong>ICE</strong>Calculator.com</h1>
</div>
<div id=“text2”>
<h2 align=“left”>&nbsp;<strong>I</strong>nterruption <strong>C</strong>ost
<strong>E</strong>stimate
</br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp
&nbsp;&nbsp;&nbsp;Calculator</h2>
</div>
</div>
Yes, I admit I used hard space code to center the word ‘Calculator’, but at the time I
was under deadline and I had to work quickly. And the end result works.
And here’s the CSS:
#header {
background-color: #3399FF;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
border: 2px solid #0033FF;
padding: 0px;
width: 900px;
float: left;
}
#header #text1 {
width: 440px;
float: left;
}
#header #text2 {
width: 310px;
float: right;
text-align: left;
vertical-align: middle;
}
You’ll notice in the first div there’s vendor-specific code, which means the rounded
corners will not appear in Internet Explorer.
The original HTML code for the Main Menu consisted of over 3,000 characters using
table tags. In the interest of saving space, I won’t repeat the code here. Instead, I’ll

Amity Directorate of Distance and Online Education


Building Dynamic Web Pages using Java Script and VBScript 61

provide the HTML and CSS for the rewritten code. Here’s the HTML for both the side
Notes
menu and the main window:
<div id=“sidemenu”>
Home</br></br>
<a href=“about.htm”>About the Calculator</a></br></br>
<a href=“disclaimer.htm”>Disclaimer</a></br></br>
<a href=“relevant-reports.htm”>Relevant Reports</a></br></br>
<a href=‘mailto:webmaster@fscgroup.com’>Contact Us</a>
</div>
<div id=“mainwindow”>
<a href=“1”> Estimate Interruption Costs
</a></br> Estimate the cost per event, cost per average kW, cost per unserved kWh
and the total cost of unreliability.
</br></br>
<a href=“2”> Estimate Value of Reliability Improvement in a Static Environment
</a></br> Estimate the value associated with a given reliability improvement. The
environment is “static” because the expected reliability with and without the improvement
does not change over time.
</br></br>
<a href=“3”> Estimate Value of Reliability Improvement in a Dynamic Environment
</a></br> Estimates the value associated with a given reliability improvement.
The environment is “dynamic” because the expected reliability with and without the
improvement changes over time based on forecasts of SAIFI, SAIDI and CAIDI.
</div>
And the CSS for the side menu and the main window:
#sidemenu {
background-color: #ffffff;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
border: 4px solid #6495ed;
padding: 20px;
width: 160px;
height: 250px;
float: left;
text-align:left;
}
#mainwindow {
background-color: #ffffff;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
border: 4px solid #556b2f;
padding: 20px;
width: 630px;

Amity Directorate of Distance and Online Education


62 Web-Enabled Business Processes
height: 250px;
Notes
float: right;
text-align:left;
}
Between the HTML and the CSS, the total character count comes to a little over
1,100. The difference between using tables and div tags here comes close to 2,000
characters, which is a world of difference.
I hope this case study provides a useful lesson—using CSS and not table tags will
great reduce the amount of code that you have to write. Using CSS also allows you to
design your page in a much more modern sense.

2.17 Further Readings

TEXT BOOKS
1. Web Technology – N.P. Goplan and J. Akilandeswari
2. Internet Technology and Web Design – ISRD Group
3. HTML and Web Designing – Kris Jamsa and Konrad King
4. Ajax for Beginners – Ivon Bayross and Sharanam Shah

REFERENCES
1. Teach Yourself Web Technologies – Ivan Bayross – Reprinted 2011, Second
Edition
2. Web Technology – Ramesh Bangia – Reprint 2008
3. HTML for Beginners – Firuza Aibava – Second Edition
4. Internet and Web Design – Ramesh Bangia, Firewall Media
5. Web Design – Jenkins, Wiley India
6. HTML and Web Designing – Kris Jama and Konrad King, Tata McGraw Hill
Publishing Pvt. Ltd.
7. Using HTML 4, XML and Java 1.2 – Eric Ladd and Jin O’ Donwell, Prentice Hall
of India, New Delhi
8. Web Technology and Design – C. Xavier, New Age International Publishers
9. Java Server Pages – Ivan Bayross, Shroff Publishers & Distributors Pvt. Ltd,.
Delhi
10. Teach Yourself web Technologies – Ivon Bayross , BPB Publications – 2002
11. Web Programming – Chris Bates, Wiley – Dreamtech India Pvt. Ltd.

Amity Directorate of Distance and Online Education

You might also like