Chapter 3:  Forms

When you build a web page that requires JavaScript, in many cases you'll be using a form and its elements: text inputs, radio buttons, select menus, etc. Here you will learn how to create forms, retrieve data from them, and how to create functions using the data.

Creating Forms

In chapter 1 you've already encountered the FORM tag, which surrounded Button objects. So far we had no use for it.

1
2
3
4
5
6
7
8
9

<HTML>
<HEAD> <TITLE>Creating Forms</TITLE> </HEAD>
<BODY>
<FORM NAME= "simple_form">
<INPUT TYPE = text NAME = "t_box1">
<INPUT TYPE = button VALUE = "submit">
</FORM>
</BODY>
</HTML>


Example 3.1: A form containing a text field and a button.

The example above creates a form named "simple_form" with a text field and a button. Whenever you refer to anything in JavaScript, you do so by name. Thus the NAME tag (line 4 & 5) is important.

Do you recall our analogy of objects with a car? In there we talked about how to access various properties of the car "Rock". To get to the interior property, we simply had to write Rock.interior. Thus to retrieve the user's input from the text field, you simply write document.simple_form.t_box1.value. Likewise, you refer to the form by document.simple_form.

Form Inputs

Form inputs are the information that the user provides, such as text in text area, button clicks, etc. Next example demonstrates how to handle inputs.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

......
<SCRIPT Language="JavaScript">
<!--
function handleButton(input){

var name = input.name_field.value;
disp = window.open("","window1","width=300,height=200,resizeable=yes");
if(disp.opener == null) disp.opener = window;
disp.opener.name = "disp_opener";
disp.document.write("Hello, "+name+". Welcome to the show.");
disp.document.close();

}
//-->
</SCRIPT>
</HEAD>

<BODY>
<H2>Please enter your name below and click SUBMIT.</H2>
<FORM NAME= "box">
<INPUT TYPE = text NAME = "name_field">
<INPUT TYPE = button VALUE = "SUBMIT" onClick="handleButton(this.form);">
</FORM>
......


Example 3.2: A form with a text field and a button. When the button is clicked, a new window pops up. Click here to see the example in a browser.

The extra feature added in this example is the onClick handler in line 21 and the handleButton function in line 3-12.

When you refer to the form using its full name, you would write document.box. But if you are working inside the form, i.e. if you are inside the "box" form tags, then you can refer to it as this. It's like calling yourself as "I", not by your name. The use of this may seem confusing in the beginning, but if you want to learn JavaScript further, you'd probably want to familiarize yourself with it.

In line 21, you will notice that this.form is passed in as the argument. Here, this refers to the button (not the form, since we are inside the button INPUT tag), and form refers to the form in which the button is contained. Thus this.form is equivalent to document.box, the form's name.

In line 3, we declare a function handleButton. The argument it accepts is named input, which we expect to be a form. In line 5, we want to extract the text inside the text field. We refer to the text by input.name_field.value and assign it to a variable name. Then we open a new window and call it disp. This is almost the same as the remote control example we've seen in chapter 2.

In line 9, we concatenate several strings to write a short message in a new window through the document.write function. So if the user types in "Jones", the new window displays "Hello, Jones. Welcome to the show.".


Exercise 6: Login Page

Create a form with three text fields, one labeled "First Name", another "Last Name", and the third as "Password". Create a login button and a reset button. For example, if the user types in "John", "Doe", and "111" in the textfields respectively, a new window should pop up saying, "Hello, John Doe. Thank you for loggin in." If the user types in anything other than 111 as the password, the new window should say somthing like, "Incorrect password. Please try again.". When the user presses the reset button, all the textfields should become empty.

Password Field: By setting "TYPE = password" for the password textfield, you can have the asterisk (*) characters echo the actual characters.


Validating Form Inputs

Let's go back to the previous example. Suppose this is a very simple guest book, and you want the user to enter the first and last name. Since the name is going into your database, you don't want to accept blank entries and incomplete entries. You can write a JavaScript function that will validate entries before you accept them.

Take a look at Example 3.3. Here, the user is asked to give the name and the phone number. The phone number is checked for the xxx-xxx-xxxx format.

Here is a portion of the BODY section:

<FORM NAME= "box">
Name: <INPUT TYPE = text NAME = "name_field"><BR>
Phone: <INPUT TYPE = text NAME = "phone">
<P><INPUT TYPE = button VALUE = "SUBMIT" onClick="checkForm(this.form);">
</FORM>

When the button is clicked, we call checkForm(this.form), where 'this.form' is equivalent to 'document.box'. Here is the code for checkForm function:

1

2
3

4

5


6
7
8
9
10
11

function checkForm(input){

var n = input.name_field.value;
var p = input.phone.value;

if( check(n,p) ){

disp = window.open("","window1","width=300,height=200,resizeable=yes");
if(disp.opener == null) disp.opener = window;
disp.opener.name = "disp_opener";
disp.document.write("Hello, "+n+". Welcome to our store.");
disp.document.write("<BR>Here is your phone number: "+p+".");
disp.document.write("<BR>Thank you for your business.");
disp.document.close();

}

}

In line 1, we have the usual function declaration. In line 2-3, we obtain the user's input in the name_field and phone textfields and assign them to variable n and p, respectively. In line 4, we have an if-statement, where we call function check(n,p). As we will see soon, check takes in two strings. It checks to see that the first one is not empty, and that the second one is in the form of phone number by calling another function. Only when both strings are in the correct format, does it return true. So if check(n,p) returns true, line 5-11 are executed -- this is almost the same as example 3.2.

Here is the code for the check function:

1

2

3
4
5


6

7

8
9



10

function check(name, pn){

if (name=="" || name==" "){

alert("Plase enter your name.");
document.box.name_field.focus();
return false;

}
if(!phoneNumCheck(pn)){

alert("The phone number must be in the following format: 222-222-2222");
document.box.phone.focus();
return false;

}

return true;

}

In line 2, we check for two condition: if name is equal to "" (thus blank entry) OR if name is equal to " "(thus a space), then line 3-5 is executed. Here, '||' is the OR operator. The OR operator (||) returns true if one of the conditions are true. The opposite is the AND operator (&&). Another logical operator is the NOT operator (!).

In line 3, we alert the user to enter the name. In line 4, focus() brings the cursor to the specified HTML element, i.e., document.box.name_field. Then we return false, and the function terminates by returning to the caller (checkForm function).

Suppose the user enters something in the name_field textfield. Next we check for the phone number's syntax in line 6. Here we see the NOT operator. As we will see shortly again, phoneNumCheck returns true if the argument is in the form of a phone number. So we want to check if phoneNumCheck(pn) returns false. So if phoneNumCheck is NOT true, i.e. false, then line 7-9 is executed.

Finally, let's analyze the phoneNumCheck function.

1

2
3

4
5


6
7

8
9

10
11
12

13
14
15

 

16

function phoneNumCheck(number){

//check for blank entry
if (number=="" || number==" ") return false;

//check for the xxx-xxx-xxxx format
if ( number.indexOf("-")!=3 || number.indexOf("-",4)!=7 || number.length!=12)
return false;

//we extract all the numbers from the entry, excluding the hyphens
var num = number.substr(0,3);
num = num.concat(number.substr(4,3));
num = num.concat(number.substr(8,4));

//now we check that only digits are entered
var c;
for( i=0; i<10; i++ ){

//convert the i-th character to ascii code value
c = num.charCodeAt(i);
if( (c<48) || (c>57) ) return false;

}

return true;

}

The phoneNumCheck takes in number, which we expect to be a string. In here we first check that number is not blank (line2-3). If it is, then we return false and terminate the function. If that's not true, then we go to line 5, where we check for three conditions: the location of the first hyphen after the area code, the location of the second hyphen, then the length of the string. There are two types of indexOf function:

String.indexOf("c") -->returns the location of the first 'c' in the string. You can test for any character. If the character is not found, -1 is returned.

String.indexOf("c", i) --> returns the location of the first 'c' in the string, starting from the location i. If not found, -1 is returned.

Note that index counting starts with 0. Here is a quick example:

var strTest = "elephant";
var charOne = strTest.indexOf("e");
var charTwo = strTest.indexOf("e", 1);
var charThree = strTest.indexOf("m");


//charOne is assigned 0.
//charTwo is assigned 2
//charThree is assigned -1, since m is not found in "elephant"

So, if the index of first hyphen is not equal to 3 (!=3), or if that of second hyphen is not 7, we return false. Also if the length of number is not 12, then we also return false (You can access the length property of any string by StringName.length).

In line 7-9, we extract only the digits of the phone number. String.substr(start_index, how_many) is a built-in JavaScript function. It extracts "how_many" characters from the String, starting from the "start_index". Say that the user entered 234-443-1423 as the phone number. After line 7, num is assigned "234". In line 8, number.substr(4,3) returns "443", which is concatenated to the previous "234" by String.concat function. Suppose we simply wrote num = number.substr(4,3) in line 8. Then num would become "443", not "234443" as we intend to do. Finally we extract the last four digits of the phone number in line 9 (num would be "2344431423").

Now we want to check that the phone number has only digits. Line 11-15 accomplishes this. Line 11 declares variable c, which will be used in the for-loop. The method num.charCodeAt(i) in line 14 returns the ascii value of the i-th character of num. In ascii, character 0-9 has the value of 48-57. So we know that if c is not between 48 and 57, the phone number has characters other than digits. If so, we return false in line 15. For a simple table of ascii codes, take a look at: http://members.tripod.com/~plangford/index.html.

When all these tests are satisfied, the function returns true and terminates (line 16).

Other HTML Form Elements

Check Boxes

Syntax: <INPUT TYPE=checkbox NAME="some_name" VALUE="some_value" CHECKED>

Usage: If you want the box to be checked when the form is loaded, type in the optional CHECKED. You can also pass in a value if desired. To test if the check box is checked, test Checkbox.checked property. It returns true if the checkbox is checked. Checkbox.value property returns the value that was passed in from the input.

Radio Buttons

Syntax: <INPUT TYPE= radio NAME="group_name" VALUE="some_value" CHECKED>

Usage: Radio buttons are used when you want an exclusive selection. Usually you have several buttons in a group, and when one is checked, the other becomes unchecked. So all the buttons in the group are given the same NAME and differs in their VALUE. The syntax for retrieving checked state and value is the same as check boxes.

Lists/Menus

Syntax: <SELECT NAME="list_name">

<OPTION VALUE="value_1">Option 1</OPTION>
<OPTION VALUE="value_2">Option 2</OPTION>

</SELECT>

Usage: You can have as many options you want in the list. If you want the user to be able to choose more than one option, type MULTIPLE in the SELECT tag.


Exercise 7: Subscription Form

Make a web page that looks like this:

The important requirements of the design:

Of the functionality:

After the user clicks on "Sign Me Up" button, a new window should pop up confirming the sign-up. For example, if the user's information was

John Doe, CPU BOX 273333, Rochester, NY 14627, johndoe@mail.rochester.edu, Weekly subscription,

The new window should say:

Thank you, John Doe.
Our newsletter will be mailed to you WEEKLY to this address:

CPU BOX 273433
Rochester, NY 14627

Have a nice day!


Back to the Top
To the Table of Contents

Last Updated September 9, 2000 by Grace Pok