Chapter 3: Forms, Input Elements, and Event Handlers

Before your JavaScript can process data using arithmetic and logical operations, it needs to collect input from its user. HTML allows you to place graphical user interface (GUI) elements on your web page that allow the user to interact with and control your JavaScript application. This chapter lists various interface elements that you may add to your web page, and how user interaction with these elements may be used to initiate the execution of associated functions.

3.1 Forms and Input Elements

The user interface for a JavaScript application is the part of the web page with which the user can interact. For instance, you may have typed expressions and assignment statements in the Try it sections of Chapter 2.The boxes in which you typed in text, the buttons that you clicked and so on together comprise user interfaces for those rather primitive JavaScript applications.The primary element of the interface is the form.A form acts as a container for other elements of your program.That is, all other user interaction elements are embedded in a form.However, the form itself has no on-screen presence.You do not see any indication on a rendered web page of the beginning or the end of a form.

You start a form in your HTML source using the <FORM> tag.As you might expect, a form ends with the </FORM> tag.Other elements of the user interface are placed between these tags.Interspersed among these tags could be other non-interactive elements of HTML, including tables, emphasized text, font specifications and so on.However, you cannot embed one form within another. It is necessary to assign a name to each form that you create. The name that you assign a form will be used in your JavaScript code to access a modify the elements embedded in the form. You can assign a name to a form by adding the NAME attribute to your form tag and assigning it an appropriate value. Ensure that the name you assign a form conforms to the rules listed for JavaScript variables. You can refer to your form in JavaScript using the notation document.formname. Here is an example of an HTML form,

<FORM NAME=myFirstForm>

<!-- input elements go here -->

</FORM>
 

When you want to access interface elements in the form above, you would use and expression of the form document.myFirstForm.elementname, where elementname is the name of the element in question.

Listed below are most of the commonly used HTML input elements and their descriptions:

Textbox:

Textbox is one of the most common input elements. Use it when you want a user to enter one line of textual input. The <INPUT> HTML tag, with the TYPE attribute set to TEXT can be used to create textboxes within your HTML forms. Be sure to assign assign each textbox a name using the NAME attribute. This property of the textbox will be used in JavaScript code to access and modify the text that appears in the element. You can access the value in a textbox using the value property. We will use this property in the next section when we discuss event handlers. Set the width of the textbox by assigning a numeric value to the optional SIZE property of the <INPUT> tag. The textbox below is produced using the following lines of HTML:
 

<INPUT TYPE=TEXT NAME=username SIZE=10>

produces the the following textbox

 
Observe that the name of the textbox (username) is itself not visible on the rendered web page.  You can access the text typed in to the textbox above using the expression document.formname.username.value, where formname is the name of the form that contains this textbox.

Note!  The value property of a textbox contains a string value.  If you expect to find a numeric value in a textbox, convert the string in the value property using the Number() function.  For instance, the following statement takes a string value in a textbox called ageBox and converts it to an integer:
age = Number ( document.surveyform.ageBox.value )


Try this: In the box below type in HTML tags for two textboxes, one with the name "higher" and the other with the name "lower". Then click the "Show me!" button to see what you've created.

 
First tag (for the textbox named "higher")
Second tag (for the textbox named "lower")


Textareas:
Textareas are essentially multi-line textboxes. That is, they can be used to get user input that spans multiple lines, and can be used to display output that appears on multiple lines. Use the <TEXTAREA> tag to create a textarea element on your web page. Terminate the textarea element with a corresponding </TEXTAREA> tag. Any text that appears in between these two tags appears as the default value of this element. As always, use the NAME attribute to specify a name for the textbox. You can also set the number of rows and columns in a textarea element using the ROWS and COLS attributes respectively. When the number of lines in the textarea exceeds the number of rows specified in the ROWS attribute a vertical scroll bar appears at the right margin of the element. In your JavaScript program, use the value property to retrieve or change the text stored in a textarea element. Shown below are the HTML code and the displayed version of a textarea element.
<TEXTAREA NAME=outputbox ROWS=10 COLS=60>This text appears inside the textarea, doesn't it?</TEXTAREA>
produces the following textarea element
As in the case of the textbox, you can access the contents of this textarea using the expression document.formname.outputbox.value.


Try this: Type in the HTML tags for a TEXTAREA box named "multiply", with 11 rows and 50 columns. Make sure you end the TEXTAREA with an appropriate end tag. Click on the button captioned "Show me!" to see your creation in a new window.

Type in the complete tag for a TEXTAREA element named "multiply"


Buttons
Almost every form that you create will have one or more buttons (or command buttons) that a user must click in order to initiate computation. You place buttons on your web page using the <INPUT> tag with the TYPE attribute set to BUTTON. You can set the caption to appear on a button using the VALUE tag. The NAME attribute, however, is not very important for button elements. Two special kinds of buttons are especially important: the submit button and the reset button. While the former is not essential in the context of JavaScript programming, the latter is. Use the reset button to clean the contents of a form and reset it to its original state. Shown below are a command button and a reset button, along with the HTML source that created them


<INPUT TYPE=BUTTON VALUE="Click me for good luck!"><BR>

Type some text into this box and then click on the button below:

<INPUT TYPE=text NAME=junkinput><BR>

<INPUT TYPE=RESET>

produces the following output


Type some text into this box and then click on the button below: 

Try this: In the box below type in the HTML tag for a button captioned "ClickMe!". Then click on the "Show Me!" button to see if you have got it right.

Type the tag for a button captioned "ClickMe!" 


Checkboxes
When you require the user to answer a "Yes or No" type question, a checkbox might be appropriate. The user can place a check in a checkbox by clicking one on the box. Clicking it again will remove the check mark. Use the <INPUT> HTML tag with the TYPE attribute set to CHECKBOX to create a checkbox element. You may create as many checkboxes as necessary in your form. However, ensure that all checkboxes are named, and that each checkbox has a distinct name. You may find the state of a checkbox in your JavaScript using the checked property. This property has a value of true if the box is checked, and false otherwise.  Shown below is a checkbox and associated HTML code:


Do you like programming in JavaScript? <INPUT TYPE=checkbox NAME=userOption>

Do you like programming in JavaScript? 


Try this: In the box below type in the HTML tag for two checkboxes, one named "haveSUV" and the other name "haveDVD". Caption the first checkbox with the question "Do you own an SUV?" and the second with "Do you have a DVD player?"

Type HTML code for the first checkbox
Type HTML code for the second checkbox


Radio buttons
Use radio buttons to have the user select one of many choices. Radio buttons resemble checkboxes. However, only one of a group of radio buttons may be selected at any given time. Each radio button in a group must be individually defined in HTML. Use the <INPUT> HTML tag with TYPE set to radio to create a radio button on your form. All radio buttons in a group must have the same NAME. Their VALUE atteributes should differ from each other. You can have one of the radio buttons selected by default by using the CHECKED attribute for that element.  The The radio buttons in the box below were created using the following HTML code:

How many children do you have?<BR>
<INPUT TYPE=radio NAME=numChildren VALUE=0> None<BR>
<INPUT TYPE=radio NAME=numChildren VALUE=1> One<BR>
<INPUT TYPE=radio NAME=numChildren VALUE=2 CHECKED> Two<BR>
<INPUT TYPE=radio NAME=numChildren VALUE=3> Three or more<BR>

How many children do you have?
None
One
Two
Three or more
Your program  can refer to each individual radio button in a group using the subscript notation.  In this notation you access a specific radio button by stating the name of its  group followed by the "position" of this radio button in the group in square brackets. The first radio button is at "position" 0, the second is at "position" 1 and so on.  For instance, the first radio button in the group above can be accessed as document.formname.numChildren[0], the second as document.formname.numChildren[1] and so on.  As in the case of checkboxes, you can use the checked (boolean) attribute of each radio button to find its status. 


Drop down lists

When you want the user to select one option from a long list of options, radio buttons may occupy too much screen space and be unwieldy to program. In such a situation it may be pertinent to use drop down lists instead. Use the <SELECT> HTML tag to create drop down lists. List each option in such a drop down list using an <OPTION> tag. See the example below:

Select a movie from the following list 

was produces using the following HTML code:

<B>Select a movie from the following list </B>
                <SELECT NAME="MovieChoice">
                <OPTION SELECTED>One ... </OPTION>
                <OPTION>Two ... </OPTION>
                <OPTION>The Three Musketeers </OPTION>
                <OPTION> Fourth</OPTION>
                <OPTION>The Fifth Element </OPTION>
                <OPTION>The Sixth Sense </OPTION>
                <OPTION>Seven Monkeys </OPTION>
                <OPTION>Eight days of Summer </OPTION>
</SELECT>
In your JavaScript code you can find which option in the list was selected using the selectedIndex property of the <SELECT> element. Options are number in sequence, with the first number in the list having an index value of 0 (zero).  Thus, for instance, the term document.formname.MovieChoice.selectedIndex would give you the value '0' if the first movie was selected, a value of '1' if the second movie was selected, and so on to a value of '7' if the last movie was selected in the drop down list above.

3.2 Event handlers

A user action on any element of your form is considered an event.  This includes mouse movement, mouse clicks, typing on the keyboard and so on.  Frequently you would want some JavaScript code to be executed in response to a user event.  For instance, consider writing a JavaScript application that converts dollar amounts to French Francs.  In such an application you might want the currency conversion function (assuming you have written one) to be executed when the user clicks on a "Convert" button on the form.  That is, you want to "handle" (take care of) the response for a click of the mouse on this button.  An "event handler" is a piece of JavaScript text that you associate with some kind category of event on a particular user interface element.   Various user interface elements respond to various events, and not all events are "interesting" for all elements---while a mouse click on a button might signal the user's interest in the initiation of some calculation, a mouse click on a textarea element is not quite as "interesting". The most common way of creating event handlers is by specifying some function to be executed when an event occurs.  We shall use this method in all our examples.

To assign an event handler for an interface element , add an event handler attribute to the tag.  Put the handling function as the value for the attribute. The general syntax is

<TAG eventHandler="JavaScript Code">
where TAG is an HTML tag, eventHandler is the name of the event handler, and JavaScript Code is a function call.

For example, suppose you have created a JavaScript function called compute. You can have this function called when the user clicks a button by assigning the function call to the button's onClick event handler:

<INPUT TYPE="button" VALUE="Calculate" onClick="compute()">
Listed below are some events, the elements that they apply to, and the event handler to be used for such an event.

  JavaScript event handlers

 
Event Applies to Occurs when Event handler
Blur
windows and all form elements User removes input focus from window or form element
onBlur
Change
text fields, textareas, select lists User changes value of element
onChange
Click
buttons, radio buttons, checkboxes, submit buttons, reset buttons User clicks form element or link
onClick
Focus
windows and all form elements User gives input focus to window or form element
onFocus
KeyDown
text areas User depresses a key
onKeyDown
KeyPress
text areas User presses or holds down a key
onKeyPress
KeyUp
text areas User releases a key
onKeyUp
MouseDown
documents, buttons User depresses a mouse button
onMouseDown
MouseMove
nothing by default User moves the cursor
onMouseMove
MouseUp
documents, buttons, links User releases a mouse button
onMouseUp


Try this:  You are given the following JavaScript function and its associated form (which is as yet incomplete).  The completed version of this program implements a primitive calculator that has only one operation: multiplication.  The user would enter a number in each of the top two textboxes, and then click on a button to obtain the product of those two numbers
<HEAD>
<SCRIPT LANGUAGE="JavaScript">

function prodThem ( )
{
        firstNumber = document.addForm.first.value
        secondNumber = document.addForm.second.value
        thirdNumber = firstNumber * secondNumber
        document.addForm.third.value = thirdNumber
}

</SCRIPT>
</HEAD>

<BODY>
<FORM NAME=addForm>

First number: <INPUT TYPE=TEXT NAME=first SIZE=10>

Second number: <INPUT TYPE=TEXT NAME=second SIZE=10>


Product: <INPUT TYPE=TEXT NAME=third SIZE=10> </FORM>
</BODY>
What's missing in the form above is the tag for a button captioned "Multiply" whose onClick event handler calls the function prodThem.   Fill in what you think would be an appropriate tag and then click on any part of this window outside the textbox.

Project 3

Dr. Krishnan assigns final grades in his CSC 120 class based on the following weights for various elements of the course:
 
Course element Weight
Final exam 25%
Test 1 15%
Test 2 15 %
Programming Assignment 1 15%
Programming Assignment 2 15%
Programming Assignment 3 15%

Write a program that accepts a students grades on each of the three quizzes, the two tests and the final examination, and outputs the overall numeric average of the student.  Create a user interface that includes tables, and well positioned input elements.  Include two buttons, one captioned "Grade" and the other a "Reset" button.  On clicking the first button the student's grade should be displayed in a textbox.  The second button should clear the contents of the form.