Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Mzuzu University

Department of Information and Communication

Technology

(ICT)

ICT 2304 – Web Design

2013 Academic Year

Lab Script 4

Using JavaScript

(Handling Form Data and other JavaScript Related Topics)

1
Contents

1. Introduction ............................................................................................................................... 3
2. Objectives ................................................................................................................................... 3
3. Background ................................................................................................................................ 3
4. Handling Form Data ................................................................................................................ 4
4.1. Creating our First HTML page ........................................................................................ 4
4.2. Adding a script. .................................................................................................................. 5
4.3. Using Regular Expressions .............................................................................................. 6
4.4. Using a submit button vs button ..................................................................................... 7
4.5. Adding a stylesheet............................................................................................................ 7
4.6. Adding a second page ........................................................................................................ 7
5. Interactive GUI using JavaScript .......................................................................................... 7
5.1. Creating the page............................................................................................................... 7
6. JavaScript Object Notation ..................................................................................................... 8
7. Summary .................................................................................................................................... 9

2
1. Introduction
This laboratory is the fourth of the laboratory activities to support the ICT

2304 – Web Design course. In the previous laboratory, we practised on how to work

with JavaScript and DOM. We were interested on how to use the Document Object
Model (DOM) to transverse and manipulate elements in an HTML page. The main
objective of this laboratory activity is to practice on handling form data using
JavaScript. Also, we are going to explore how Java Script is used to manipulate the
display of elements on a web page. We will use simple examples to help us understand
how to work with JavaScript to perform these tasks. You will have to write the code for
the different sections.

2. Objectives
The objectives of this laboratory activity are to:

a) Introduce techniques in handling form data.


b) Introduce concepts in display handling using JavaScript.
c) Introduce JavaScript concepts important to current web development.

3. Background
The first part of this activity will focus on handling form data using JavaScript. In our
last laboratory activity, we looked at form data validation. We saw that form data
validation is the task of ensuring that the values provided by the user are correct. We
looked at one type of validation which ensures that the user has not left out blank
spaces.
Also, data type and format validation can be done to ensure that the data that has been
provided fits the expected format. We will look at the second part in this laboratory
activity. Additionally, we will look at how to access data from other data controls using
DOM as well as other shortcut methods.

JavaScript is widely used to manipulate page elements display .There are several
JavaScript libraries for controlling page display. We will use a simple example to
practice display concept.

3
4. Handling Form Data
The first part of the exercise will look at handling form data. We will start our task by
designing the page which will be used for the JavaScript practice. We will attach our
JavaScript code in a series of steps.

4.1. Creating our First HTML page

Open a text editor and type in the following text :

<html>
<head>
<title>Personal Details</title>
</head>
<body>
<form name="form1" id="form1" method="post" action="success.htm"
onsubmit="return form1_onsubmit()">

<p> Fill in your details and click on the submit button</p>

<table border ="0">

<tr>
<td><legend>First Name</legend></td>
<td><input type="text" name ="fname" id ="fname" /><br/></td></tr>
<tr> <td><legend>Surname</legend></td>
<td><input type="text" name ="sname" id ="sname" /><br/></td>
</tr>

<tr> <td><legend>Gender</legend></td>
<td><input type="radio" name ="gender" id ="gender" value="male">
Male </input><br/></td>
<td><input type="radio" name ="gender" id ="gender" value="female">
Female </input><br/></td>
</tr>

<tr>
<td><legend>Marital Status</legend></td>
<td><select id="marital" name="marital" >
<option value ="m">Married</option>
<option value ="s">Single</option>
<option value = "w">Widowed</option>
<option value ="sp">Single Parent</option>
<option value ="c">Living with Partner</option>
/><br/></td></select>
</tr>
<tr>
<td><legend>Do you have children?</legend></td>
<td><input type="radio" name="child" id="child">Yes</input></td>
<td><input type="radio" name ="child" id="child">No</input></td>
</tr>
<tr>
<td><legend>Number of Children</legend></td>
<td><select id="Nochild" name ="Nochild" >

4
<option value ="0">0</option>
<option value ="1">1</option>
<option value ="2">2</option>
<option value ="3">3</option>
<option value ="4">4</option>
</select>
</td>
</tr>

<tr>
<td><legend>E-mail</legend></td>
<td><input type = "text" name="email" id="email" /><br/></td>
</tr>
<tr>
<td></td>
<td><input type = "submit" name="submit" value="submit"
/><br/></td>

</table>
</form>

</body>
</html>

4.2. Adding a script.

Add within the head tag i.e. between <head> and </head> a <script> block as shown
below:
<script type="text/javascript" src="validate.js"></script>

Open a text editor and create a script file named validate.js. In the text editor add a
function named form1_onsubmit() like this:

function form1_onsubmit()
{…}

Now we will write code that will check if the different controls have been checked or
filled. Let’s start with the input boxes. In our last laboratory activity, we looked at
checking if data has been filled in our input boxes. Using the same approach, let’s write
the code that ensures that the text boxes have been filled.

The first step is to declare a variable which will contain the filled values. There are so
many ways of accessing a form control. Using node.value is one of ways to access the
values. The following line of code illustrates that.

fName = document.form1.fName.value;

You can do the same for the other input boxes. Now, we will need to write code which
checks if someone has entered something. You can refer to the previous laboratory
activity, on how to get this working.

5
Add variables to the script which will contain the values from the check box and select
box. What type of variables should be declared? A selected value from a select box can be
retrieved using document.formx.idx.selectedIndex;. How can we check if an option
in a select box has been selected? Sometimes, you can set an option to be a default
value.
function checkSelect(select)
{
return (select.selectedIndex > 0);
}

How can we check if a radio button ? Check the following code and change it to suit your
declared variables.

function checkRadioArray(radioButtons)
{
for (var i=0; i < radioButtons.length; i++)
{
if (radioButtons[i].checked) {
return true;
}
}
else return false;
}

4.3. Using Regular Expressions


A regular expression, also known as "regex" is a description of a pattern of text that is
matched against the data provided by the user. Regular expressions are extremely
powerful but tough to read and write. There are so many Regex available for doing
things like checking whether a given value matches an e-mail address. We will use a
simple example to check if the values entered are of string type.

In most programming languages, a regex is a string which starts with / and ends with /.
For example, we can have a regex “/xyz/”. This pattern will match any string with the
letters xyz in the given order. There can be case insensitive matches and that can be
done by adding i at the end i.e. “/xyz/i”.

Using string.match(regex)
The match method can be used to check if string fits the given pattern and it returns the
matching text. Otherwise, it returns null. It can be used for a true or false test. For
example, if we want to test if a string has only characters coming from the alphabet a to
z, then we can group that as /[a-z] +/. The following example shows just that:

6
var name = fname= document.form1.fname.value;
if (fname.match(/[a-z]+/)) { ... }

You can find more information on http://www.w3schools.com/jsref/jsref_obj_regexp.asp.

4.4. Using a submit button vs button


Using a submit button should be used with care, since cannot submitted only if a
function handling the submit event returns false. If JavaScript is disabled, still the data
is going to be submitted even if the script has not run. Therefore, it is advisable, to use a
button instead of a submit button if JavaScript is being used to handle some form data.
The equivalent onsubmit event for a button is the onclick event.

4.5. Adding a stylesheet


Create an external style sheet for the page. How do we add an external style sheet to a
page? We need to add a link tag in the header like this one.

<link rel="stylesheet" type="text/css" href="mystyle.css" />

Also, we need to create a style sheet which will contain the rule sets for styling the
elements in our page.

4.6. Adding a second page


Create a new page and name it success.htm. This page requested if our data has been
sent successfully to our server. Create a page like this one.

<html>

<body>

<h1> Thank you for registering</h1>

</body>

</html>

5. Interactive GUI using JavaScript


The objective of this task is to practice using basic JavaScript and user interface
controls to create a web page that responds to user actions.

5.1. Creating the page

This is a simple task which creates a web page with one paragraph. Use a text editor to
perform this task. The text file should contain something like this:

7
<html>

<body>

<p>Welcome<p>

</body>

</html>

After creating the page, you will be required to create a basic JavaScript file. This file
should be linked to the web page.

What we want in this task the text in our HTML file to change whenever a user moves a
mouse over the text. The text should change size (30pt) and colour (green). We know
that CSS style properties can be translated to properties of the .style property within
that element's DOM object. We set the colour of the error message to red in our previous
lab activity. For example, the following CSS color declaration:

#id {

color: green;

We can rewrite that in JavaScript as:

Document.getElementById(“id”).style.color = "green”;

Also, some properties have a hyphen in them, such as background-color, in JavaScript


the hyphens are removed and the following words are capitalized:

Document.getElementById(“id”).style.backgroundColor = "green";

This exercise is simple and you should be able to write the code without any problems.

6. JavaScript Object Notation

JSON is syntax for storing and exchanging text information. JSON is lightweight text-
data interchange format which is language independent. It is "self-describing" and easy
to understand.

JSON uses JavaScript syntax for describing data objects. However, it is still language
and platform independent. JSON parsers and JSON libraries exists for many different
programming languages. JSON is currently widely used as a data interchange format
for different application area. The example below from http://www.w3schools.com/json/

8
describes employees data structure. Note that the syntax is of an array of JavaScript
objects.

{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}

7. Summary
In this lab activity, we have seen how to work with JavaScript to handle form data, to
handle user actions on the UI and many more. Always remember to include server-side
validation to avoid bad data finding its way into your system.

You might also like