DAY - 19
JavaScript Forms
CGI- stands for
common gateway interface, is a mechanism for safely transporting data from a
client (a browser) to a server. It is typically used to transfer data from an
HTML form to the server.
With JavaScript at your side, you can process simple
forms without invoking the server. And when submitting the form to a CGI
program is necessary, you can have JavaScript take care of all the preliminary
requirements, such as validating input to ensure that the user has dotted every
i. In this column we'll look closely at the JavaScript-form connection,
including how to use JavaScript's form object, how to read and set form
content, and how to trigger JavaScript events by manipulating form controls.
We'll also cover how to use JavaScript to verify form input and submit the form
to a CGI program.
Creating the form
There are few differences between a straight HTML form
and a JavaScript-enhanced form. The main one being that a JavaScript form
relies on one or more event handlers, such as onClick or onSubmit. These invoke
a JavaScript action when the user does something in the form, like clicking a
button. The event handlers, which are placed with the rest of the attributes in
the HTML form tags, are invisible to a browser that don't support JavaScript.
Because of this trait, you can often use one form for both JavaScript and
non-JavaScript browsers.
Typical form control
objects -- also called "widgets" -- include the following:
·
Text box for entering a
line of text
·
Push button for selecting
an action
·
Radio buttons for making
one selection among a group of options
·
Check boxes for selecting
or deselecting a single, independent option
I won't bother enumerating all the attributes of these
controls (widgets), and how to use them in HTML. Most any reference on HTML
will provide you with the details. For use with JavaScript, you should always
remember to provide a name for the form itself, and each control you use. The
names allow you to reference the object in your JavaScript-enhanced page.
The typical form looks
like this. Notice I've provided NAME= attributes for all form controls,
including the form itself:
<FORMNAME="myform"ACTION=""METHOD="GET">
Enter something in the box: <BR>
<INPUTTYPE="text"NAME="inputbox"VALUE=""><P>
<INPUTTYPE="button"NAME="button"Value="Click"onClick="testResults(this.form)">
</FORM>
·
FORM NAME="myform" defines and names the form. Elsewhere in the
JavaScript you can reference this form by the name myform. The name
you give your form is up to you, but it should comply with JavaScript's
standard variable/function naming rules (no spaces, no weird characters except
the underscore, etc.).
·
ACTION="" defines how you want the browser to handle the
form when it is submitted to a CGI program running on the server. As this
example is not designed to submit anything, the URL for the CGI program is
omitted.
·
METHOD="GET" defines the method data is passed to the server
when the form is submitted. In this case the atttibute is puffer as the example
form does not submit anything.
·
INPUT TYPE="text" defines the text box object. This is standard
HTML markup.
·
INPUT TYPE="button" defines the button object. This is standard HTML
markup except for the onClick handler.
·
onClick="testResults(this.form)" is an event handler -- it handles an event, in
this case clicking the button. When the button is clicked, JavaScript executes
the expression within the quotes. The expression says to call the testResults
function elsewhere on the page, and pass to it the current form object.
Getting a value from a form object
Let's experiment with
obtaining values from form objects. Load the page, then type something into the
text box. Click the button, and what you typed is shown in the alert box.
Listing 1. testform.html
<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<SCRIPTLANGUAGE="JavaScript">
functiontestResults(form){
varTestVar=form.inputbox.value;
alert("You typed: "+TestVar);
}
</SCRIPT>
</HEAD>
<BODY>
<FORMNAME="myform"ACTION=""METHOD="GET">Enter something in the box: <BR>
<INPUTTYPE="text"NAME="inputbox"VALUE=""><P>
<INPUTTYPE="button"NAME="button"Value="Click"onClick="testResults(this.form)">
</FORM>
</BODY>
</HTML>
Here's how the script works. JavaScript calls the
testResults function when you click the button in the form. The testResults
function is passed the form object using the syntax this.form (the this keyword references the button control; formis a property of the button control and represents the
form object). I've given the form object the name form inside
the testResult function, but you can any name you like.
The testResults function is simple -- it merely copies
the contents of the text box to a variable named TestVar. Notice how the text
box contents was referenced. I defined the form object I wanted to use
(called form), the object within the form that I wanted
(called inputbox), and the property of that object I wanted
(the value property).
Setting a value in a form object
The value property of the
inputbox, shown in the above example, is both readable and writable. That is,
you can read whatever is typed into the box, and you can write data back into
it. The process of setting the value in a form object is just the reverse of
reading it. Here's a short example to demonstrate setting a value in a form
text box. The process is similar to the previous example, except this time
there are two buttons. Click the "Read" button and the script reads
what you typed into the text box. Click the "Write" button and the
script writes a particularly lurid phrase into the text box.
Listing 2. set_formval.html
<HTML>
<HEAD>
<TITLE>Test Input </TITLE>
<SCRIPTLANGUAGE="JavaScript">
functionreadText(form){
TestVar=form.inputbox.value;
alert("You typed: "+TestVar);
}
functionwriteText(form){
form.inputbox.value="Have a nice
day!"
}
</SCRIPT>
</HEAD>
<BODY>
<FORMNAME="myform" ACTION="" METHOD="GET">
Enter something in the box: <BR>
<INPUT TYPE="text"NAME="inputbox"VALUE=""><P>
<INPUT TYPE="button"NAME="button1"Value="Read"onClick="readText(this.form)">
<INPUT TYPE="button"NAME="button2"Value="Write"onClick="writeText(this.form)">
</FORM>
</BODY>
</HTML>
·
When you click the
"Read" button, JavaScript calls the readText function, which reads
and displays the value you entered into the text box.
·
When you click the
"Write" button, JavaScript calls the writeText function, which writes
"Have a nice day!" in the text box.
Reading other form object values
The text box is perhaps
the most common form object you'll read (or write) using JavaScript. However,
you can use JavaScript to read and write values from most other objects (note
that JavaScript cannot currently be used to read or write data using the
password text box). In addition to text boxes, JavaScript can be used with:
·
Hidden text box
(TYPE="hidden").
·
Radio button
(TYPE="radio")
·
Check box
(TYPE="checkbox")
·
Text area (<TEXT
AREA>)
·
Lists (<SELECT>)
Using Hidden Text Boxes
From a JavaScript
standpoint, hidden text boxes behave just like regular text boxes, sharing the
same properties and methods. From a user standpoint, hidden text boxes
"don't exist" because they do not appear in the form. Rather, hidden
text boxes are the means by which special information can be passed between
server and client. They can also be used to hold temporary data that you might
want to use later. Because hidden text boxes are used like standard text boxes
a separate example won't be provided here.
Using Radio Buttons
Radio buttons are used to
allow the user to select one, and only one, item from a group of options. Radio
buttons are always used in multiples; there is no logical sense in having just
one radio button on a form, because once you click on it, you can't unclick it.
If you want a simple click/unclick choice use a check box instead (see below).
To define radio buttons
for JavaScript, provide each object with the same name. JavaScript will create
an array using the name you've provided; you then reference the buttons using
the array indexes. The first button in the series is numbered 0, the second is
numbered 1, and so forth. Note that the VALUE attribute is optional for
JavaScript-only forms. You'll want to provide a value if you submit the form to
a CGI program running on the server, however.
<INPUT TYPE="radio" NAME="rad" VALUE="radio_button1" onClick=0>
<INPUT TYPE="radio" NAME="rad" VALUE="radio_button2" onClick=0>
<INPUT TYPE="radio" NAME="rad" VALUE="radio_button3" onClick=0>
<INPUT TYPE="radio" NAME="rad" VALUE="radio_button4" onClick=0>
Following is an example of
testing which button is selected. The for loop in the testButton function
cycles through all of the buttons in the "rad" group. When it finds
the button that's selected, it breaks out of the loop and displays the button
number (remember: starting from 0).
LIsting 3. form_radio.html
<HTML>
<HEAD>
<TITLE>Radio Button Test</TITLE>
<SCRIPTLANGUAGE="JavaScript">
functiontestButton(form){
for(Count=0;Count<3;Count++){
if(form.rad[Count].checked)
break;
}
alert("Button "+Count+" is selected");
}
</SCRIPT>
</BODY>
<FORMNAME="testform">
<INPUTTYPE="button"NAME="button"Value="Click"
onClick="testButton(this.form)"><BR>
<INPUTTYPE="radio"NAME="rad"Value="rad_button1"onClick=0><BR>
<INPUTTYPE="radio"NAME="rad"Value="rad_button2"onClick=0><BR>
<INPUTTYPE="radio"NAME="rad"Value="rad_button3"onClick=0><BR>
</FORM>
</HTML>
Setting a radio button
selection with HTML market is simple. If you want the form to initially appear
with a given radio button selected, add the CHECKED attribute to the HTML
markup for that button:
<INPUTTYPE="radio"NAME="rad"Value="rad_button1"CHECKEDonClick=0>
You can also set the
button selection programmatically with JavaScript, using the checked property.
Specify the index of the radio button array you want to checked.
form.rad[0].checked=true;// sets to first button in the rad group
Using Check Boxes
Check boxes are
stand-alone elements; that is, they don't interact with neighboring elements
like radio buttons do. Therefore they are a bit easier to use. Using JavaScript
you can test if a check box is checked using the checked property, as shown
here. Likewise, you can set the checked property to add or remove the checkmark
from a check box. In this example an alert message tells you if the first check
box is checked. The value is true if the box is checked; false if it is not.
Listing 4. form_check.html
<HTML>
<HEAD>
<TITLE>Checkbox Test</TITLE>
<SCRIPTLANGUAGE="JavaScript">
functiontestButton(form){
alert(form.check1.checked);
}
</SCRIPT>
</BODY>
<FORMNAME="testform">
<INPUTTYPE="button"NAME="button"Value="Click"
onClick="testButton(this.form)"><BR>
<INPUTTYPE="checkbox"NAME="check1"Value="Check1">Checkbox 1<BR>
<INPUTTYPE="checkbox"NAME="check2"Value="Check2">Checkbox 2<BR>
<INPUTTYPE="checkbox"NAME="check3"Value="Check3">Checkbox 3<BR>
</FORM>
</BODY>
</HTML>
As with the radio button
object, add a CHECKED attribute to the HTML markup for that check box you wish
to be initially check when the form is first loaded.
<INPUTTYPE="checkbox"NAME="check1"Value="0"CHECKED>Checkbox 1>
You can also set the
button selection programmatically with JavaScript, using the checked property.
Specify the name of the checkbox you want to check, as in
form.check1.checked=true;
Using Text Areas
Text areas are used for
multiple-line text entry. The default size of the text box is 1 row by 20
characters. You can change the size using the COLS and ROWS attributes. Here's
a typical example of a text area with a text box 40 characters wide by 7 rows:
<TEXTAREANAME="myarea"COLS="40"ROWS="7">
</TEXTAREA>
You can use JavaScript to
read the contents of the text area box. This is done with the value
property.
Listing 5. form_textarea.html
<HTML>
<HEAD>
<TITLE>Text Area Test</TITLE>
<SCRIPTLANGUAGE="JavaScript">
functionseeTextArea(form){
alert(form.myarea.value);
}
</SCRIPT>
</HEAD>
<BODY>
<FORMNAME="myform">
<INPUTTYPE="button"NAME="button3"Value="Test"
onClick="seeTextArea(this.form)">
<TEXTAREANAME="myarea"COLS="40"ROWS="5">
</TEXTAREA>
</FORM>
</BODY>
</HTML>
You can preload text into
the text area in either of two ways. One method is to enclose text between the
<TEXTAREA> and </TEXTAREA> tags. This method is useful if you wish
to include hard returns, as these are retained in the text area box. Or, you
can set it programmatically with JavaScript using the following syntax:
form.textarea.value="Text goes here";
·
form is the name of the form.
·
textarea is the name of the textarea.
·
"Text goes here" is the text you want to display
No comments:
Post a Comment
Give your valuable feedback