Chapter 11. Making Forms Perform

CONTENTS

CONTENTS>>

  •  The Many Types of Forms Elements in HTML
  •  All Text Entries Are Strings
  •  Passing Data Between Forms and Variables
  •  Forms as Arrays
  •  Types of Forms
  •  Buttons and Their Events
  •  Summary

Forms used in conjunction with JavaScript can provide a wide source of engaging and interactive pages for the designer. Besides being used as crucibles for information such as name, address, and email, forms are used to respond to different activities by the user. Everything from games to quizzes to online calculators can be created using HTML forms and JavaScript together. So, if you thought forms were boring, take a look and see what you can create using them with JavaScript.

Two critical tasks await JavaScript. First, JavaScript can take the data within the forms and pass it through variables from one place to another on an HTML page or even to different HTML pages. By passing form data in variables, JavaScript can be more precisely interactive with HTML than a generic set of data. Second, JavaScript serves as a form-verification medium. All data headed for a database or back-end middleware like ASP and PHP can first be checked for accuracy and completeness by JavaScript. For example, JavaScript can make sure that any email addresses that are entered into a form have the @ sign and, if the @ sign is missing, alert the viewer to that fact. Beginning in Chapter 14, "Using PHP with JavaScript," where the book begins examining server-side scripting with JavaScript as an intermediary, you will see how the form data can be checked first by JavaScript before the variables in the forms are sent to the back end.

The Many Types of Forms Elements in HTML

The forms element in HTML is more like a mega-element with many other elements within. Each of the HTML forms elements has a number of properties, which in HTML are known as "attributes."

  • forms element (mega-element)

  • forms elements (e.g., text boxes, buttons, etc.)

  • form attributes (e.g., name, size, width, etc.)

In looking at an HTML page with a form, with the exception of the <textarea> container, the only container within the forms object is the form itself. That is, the forms element has an opening and closing tag, but none of the elements within the container has closing tags:

<form>        <form element 1>        <form element 2>        <form element 3>  </form>

As far as JavaScript is concerned, the forms object is one big array. Each new form container is an element of the document array, and each element within each forms object is an element of that form's array. Later in this chapter, form arrays are examined in detail, but for now, it is important to understand that an array relationship exists between JavaScript and HTML forms.

The following list summarizes all of the form objects in HTML tags, arranged by type:

HTML element

Text input

  • <input type=text>

  • <textarea> </textarea>

  • <input type=hidden>

  • <input type=file>

  • <input type=password>

Buttons

  • <input type=button>

  • <input type=reset>

  • <input type=submit>

  • <input type=radio>

  • <input type=checkbox>

  • <input type=image>

Menu

  • <select>

  • <select multiple>

  • <option>

JavaScript's relationship to the HTML tags has been illustrated in numerous examples in previous chapters, but it bears repeating. As a general format, the relationship between the objects and properties in JavaScript is the same as between the form order and name attributes in HTML. The following HTML tags:

<form name="alpha">        <input type =text name="beta">  </form>

are addressed like this in JavaScript:

document.alpha.beta; 

Attributes of the secondary elements (forms is the primary element) are treated as properties of the secondary elements. For example, if you wanted to know how long a string in a text box is, you would address it as follows:

document.alpha.beta.value.length; 

You might wonder why the value and the length properties had to be included instead of just length. The property itself has no length unless you're looking for the length of an array. However, the value assigned to the property does have a length, and that is what you want. If you entered this, you could find out the length of the array, not any of the values in the elements of the form:

document.alpha.length; 

All Text Entries Are Strings

Another feature of form data to remember is that it treats all entries as strings. For example, in setting up an online boutique, you might want to perform math on data entered by the user. The following little script attempts to add two numbers:

<html>  <head>  <title> Text Box Math </title>  <script language="JavaScript">  function addEmUp( ){       var sum=document.calc.aOne.value + document.calc.aTwo.value;        alert(sum);        }  </script>  </head>  <body bgcolor="#ffffaa">  <h4>Enter 2 numbers and press the Sum button.</h4>  <form name="calc">  <input name="aOne" type=text ><P>  <input name="aTwo" type=text ><P>  <input type=button value="Sum" onClick="addEmUp( )">  </form>  </body>  </html>

When you run the script, you will see, as shown in Figure 11.1, that instead of getting a sum, you get a string of two numbers. The script concatenated two strings instead of adding two numbers.

Figure 11.1. Instead of adding numeric values from text fields, JavaScript concate nates them.

graphics/11fig01.gif

While numbers are unsigned (they are neither integers nor floating point) in JavaScript, strings that are transformed into numbers are converted into either integers or floating-point numbers using one of the following functions:

parseInt( )  parseFloat( ) 

For example, if your string is 34.763, use parseFloat ( ) to preserve the decimal points, or use parseInt ( ) to return the integer, rounded down. By changing this line:

var sum = document.calc.aOne.value + document.calc.aTwo.value; 

to

var sum = parseFloat(document.calc.aOne.value) + parseFloat (document.calc.aTwo.  value); 

your output changes to reflect the sum of two floating-point numbers.

NOTE

If you do not want integers rounded down but you want them rounded to the nearest integer, use Math.round ( ). The Math.ceil ( ) function rounds numbers to the next highest integer, and Math.floor ( ) rounds numbers down. The Math functions can be used with either numbers or strings.

While text or textarea values are always in strings, changing them to numbers is quite easy, and JavaScript provides several functions to help you. However, the difficult part is remembering to do so!

Passing Data Between Forms and Variables

Before going on to discuss arrays, you need to understand the relationship that exists between HTML form properties and variables and values in JavaScript. You should understand something about passing data between forms and JavaScript variables. Consider the following form in an HTML page:

<html>  <body bgcolor=#BedFed>  <form name = "stateBird">        <input type="text" name="state">        <input type="text" name="bird">  </form>  </body>  </html>

The form itself is treated as an object in JavaScript, and, as was seen in previous chapters, objects are one of the data types that you can put into a JavaScript variable. The general format for using form data to a JavaScript variable is shown here:

var variableName = document.formName.propName.value; 

For example, you can define the following JavaScript variables with the values of the contents of the form like this:

<script language="JavaScript">  var state=document.stateBird.state.value;  var bird=document.stateBird.bird.value;  </script>

Note that the element names in the form are being used as variable names. Now the object values are in variables using names of properties of the form object. The data values, however, are dependent on what a user puts into the text boxes.

Putting these together along with a function and a button to fire off the function, you can see how the values of the variables change with output from a user.

formVariable.html  <html>  <head>  <script language="JavaScript">  function getBird( ){       var state=document.stateBird.state.value;        var bird=document.stateBird.bird.value;        alert("The state bird of " + state + " is the " + bird);        }  </script>  </head>  <body bgcolor=#BedFed>  <form name = "stateBird">  <input type="text" name="state">:State Name <br>  <input type="text" name="bird">: Name of State Bird<p>  <input type="button" value="Bird Button" onClick="getBird()";>  </form>  </body>  </html>

As you can see in Figure 11.2, the data entered into the form are echoed back in an alert window indicating the values in the forms were passed to JavaScript.

Figure 11.2. Data entered by users can be passed to variables in JavaScript.

graphics/11fig02.gif

By the same token that values can be passed from a form to a JavaScript variable, the opposite is true. Data in JavaScript can be passed to a form using the following general format:

var variableName = someValue;  document.formName.propName.value = variableName; 

First, the JavaScript variable is declared and given a value. Then, the form object gets its value from the variable. The process simply reverses passing data from the form to the variable. The following program shows how to pass values from a variable to a form object in HTML.

variableForm.html
<html>  <head>  <script language="JavaScript">  function putBird( )  {       var state="New Mexico";        document.stateBird.state.value=state;        var bird="Roadrunner";        document.stateBird.bird.value=bird;  }  </script>  </head>  <body bgcolor=#BedFed>  <form name = "stateBird">        <input type="text" name="state;">:State Name <br>        <input type="text" name="bird">: Name of State Bird<p>        <input type="button" value="Bird Button" onClick="putBird( )";>  </form>  </body>  </html>

Figure 11.3 shows what appears on the screen when the function fires. Until Bird Button is pressed, the two form windows are blank, indicating that the values in the JavaScript variables were indeed passed to the form object.

Figure 11.3. Data defined in JavaScript variables appears in the form windows.

graphics/11fig03.gif

Forms as Arrays

When you create a form in HTML, you create a form array. The development of an HTML form has a parallel array in JavaScript. As each form is developed, a form element is added to the array. Likewise, as each element within the form is developed, another subelement is added to the array. All forms in a form array are properties of the document object and are referenced as forms[n]. Within each forms[] element, all of the elements added in the <form> container are elements of the form[] object. Table 11.1 shows the HTML and JavaScript parallels in developing an array.

Table 11.1. Parallel HTML and JavaScript Forms and Form Elements

HTML

JavaScript

<form name="first">

document.forms[0];

<input type=text>

document.forms[0].elements[0];

<input type=button>

document.forms[0].elements[1];

<textarea></textarea>

document.forms[0].elements[2];

</form>

 

<form name="second">

document.forms[1];

<input type=text>

document.forms[1].elements[0];

<input type=button>

document.forms[1].elements[1];

<textarea></textarea>

document.forms[1].elements[2];

</form>

Note in Table 11.1 that, like all arrays, the elements begin with 0 instead of 1. Also note that, in the JavaScript for the second form, the forms[] element is equal to 1 but the first element of the forms[1] element is 0 because it is the first element of the second form. Also, note that <textarea> is treated the same as the <input> type of elements.

Forms and Elements

Because forms are numbered elements (properties) of the document object or form array, and because elements are numbered elements of the form array also, either or both of forms[] or elements[] can work with loops to enter or extract data in forms. By looping through a forms[] array, the form elements can be used in sequential order.

In the following script, a JavaScript function loops through the first of two forms. A button in the second form fires the function that sends the data to a text area that is part of the second form.

NOTE

The reference to the text area element is document.forms[1].elements[1]. Because elements[1] is the second element in the second form, you might wonder why element[0] is not addressed. The reason lies in the fact that the first element in the second form is the button, not the text area. If you used element[0], the text would attempt to stuff itself into the button.

The script itself is fairly simple; however, because of all of the table tags required to format the script, a lot of the tag code is for the table elements.

formArray.html
<html>  <head>  <title> Form Array </title>  <style type="text/css">  body {      background-color:fe718 ;       font-family:verdana       }  .inBox {      color:white;       font-family:verdana       }  h3 {      font-size:18pt;       color:a4352f       }  </style>  <script language="JavaScript">  function sendEm( ) {      var newDisplay="";       var myForm=document.enter.length;       for (var counter=0;counter < myForm;counter++) {      newDisplay += document.forms[0].elements[counter].value + "\n";       }       document.forms[1].elements[1].value = newDisplay;  }  </script>  </head>  <body>  <h3>Enter the information:</h3>  <form name="enter">  <table border="0" cellpadding="3" cellspacing="0" height="78" width="auto"  bgcolor="#8e58ad">        <tr>                          <td colspan="2"><input name="fName" type=text ><span                          class="inBox">&nbsp;&nbsp;First Name</span> </td>                          <td colspan="2"><input name="lNamename" type=text ><span                          class="inBox">&nbsp;&nbsp; Last Name</span></td>                    </tr>                    <tr>                          <td><input name="address" type=text ><span                          class="inBox">&nbsp;&nbsp; Address</span></td>                          <td><input name="city" type=text ><span                          class="inBox">&nbsp;&nbsp;City</span> </td>                          <td><input name="state" size = 2 type=text ><span                          class="inBox">&nbsp;&nbsp;State</span></td>                          <td><input name="zip" size=6 type=text ><span                          class="inBox">&nbsp;&nbsp; Zip Code</span> </td>                    </tr>                    <tr>                          <td colspan="4"><input name="email" type=text ><span                        class="inBox">&nbsp;&nbsp;Email</span> </td>                    </tr>        </table>  </form>  <form name="transfer">        <input type=button value="Transfer Array" onClick="sendEm( )"><p>        <textarea rows=8 cols=80 name="gather"></textarea>  </form>  </body>  </html>

Because text windows have similar formatting requirements to alert boxes, the escape sequence \n is used to create a new line instead of <br>, as has been employed to create a line break when document.write( ) is used to display output to a page. Figure 11.4 shows the output for the script.

Figure 11.4. You can use loops to extract and pass data between forms.

graphics/11fig04.gif

TIP

Even if you prefer to hand-code JavaScript to reduce code bloat found in the web site design applications, these tools (such as GoLive, Dreamweaver, and FrontPage) make it much easier to set up your tables. You can always make finer changes in the HTML and JavaScript code, but trying to design and format a page without some type of WYSIWYG (What You See Is What You Get wizzy-wig) application is not a challenge that most designers need.

Addressing and Naming Forms

In the previous script, most of the references to the forms were to an array. However, you might have noticed that all of the elements except for the button had a name. Naming forms is a crucial step even if you address all elements as part of an array. Your script is much clearer if you have meaningful names assigned to all of the parts rather than array references. Using names makes everything much clearer. Table 11.2 shows some samples of well-named tags and the JavaScript reference to the form elements.

Table 11.2. Clear Reference Names

HTML

JavaScript

<form name="addressBook">

document.addressBook;

<input type=text name="client">

document.addressBook.client.value ="NanoNanoTech Inc.";

<input type=text name="lawyer">

document.addressBook.lawyer.value ="Sue A. Lot";

<form name="artSupplies">

document.artSupplies.length;

<input type=text name="brushes">

document.artSupplies.brushes.value ="Camel Hair";

Not only do clearly named forms make debugging and updates a lot easier, but they also are essential for passing data to back-end sources. Beginning in Chapter 14, when JavaScript and different types of server-side programs are explored, you will find that the variable names passed to PHP, ASP, and Perl/CGI scripts are the names that you put into the HTML tags in forms. In cases when no server-side scripts exist in a web site, a smart designer still has named forms and form elements so that if a client wants a back end for a site, it's all ready to go.

Types of Forms

At the beginning of the chapter, you saw a list of different types of form attributes in HTML that JavaScript uses as sources of data input and extraction, for launching scripts, and for other action chores. This section of the chapter examines each element in the general categories established at the outset in more detail. Each of the element's JavaScript-relevant attributes are examined and discussed.

Input for Typing and Displaying

The most flexible interactive component on a web page is the text input element. As listed at the beginning of the chapter, five types of text input are found in HTML:

  • <input type=text>

  • <textarea> </textarea>

  • <input type=hidden>

  • <input type=file>

  • <input type=password>

Throughout the book and this chapter, you have seen the input tags with the text type or the textarea containers. The hidden and password input tags work in a very similar way to input text, while the input file type is quite different.

Input Text

The input text tag has four important attributes relevant to both JavaScript and using forms:

  • name

  • size

  • maxlength

  • value

Of all of these attribute, name is the most important for identifying the element and its use as a variable name in server-side scripts. size refers to the size of the text window. The default size is 20, but you will have the opportunity to change the size to fit your needs. For example, as shown in the previous example, you need only two characters for state abbreviations and six for standard size ZIP codes. For street addresses, you might want 30 or 40 spaces available.

Related to size is the maxlength attribute. The maxlength attribute forces the user to a top limit. For example, if the user attempts to put in more than two characters in a text box set up for state abbreviations, she will find that it is impossible to do so.

Often, the value attribute is left out of a tag using input text. Usually, the page designer wants the user to put in her own information that will be used by the script. However, you can use default values in a text box as a prompt for the user. The following script shows a simple example of using all of the text box attributes:

<html>  <head>  <title> Text Box </title>  <script language="JavaScript">  function tooShort( ) {       if (document.users.userName.value.length < 7) {             alert("Your username must be at least 7 characters:");        } else {             alert("Your username is accepted:");  }  }  </script>  </head>  <body bgcolor="goldenrod">  <h4>Enter a user name between 7 and 12 characters long:</h4>  <form name="users">        <input type=text name="userName" size=12 maxlength=12 value="username"><P>        <input type=button value="Check user name" onClick="tooShort( );">  </form>  </body>  </html>

Because the maximum size of word is restricted to 12 in the text attributes, using both maxlength and size, JavaScript does not have as much work to do. The function checks to see whether the length is correct and generates an alert window to announce whether the user name is acceptable. However, because the maximum length is handled by the HTML, all JavaScript has to do is to check for a length that is too short.

Textarea

The textarea container can be used as both an input and an output source of data in HTML and with JavaScript. Its key attributes are a bit different from those of the text box because both width and height must be included. The following four attributes are the most pertinent:

  • name

  • cols

  • rows

  • value

The following script shows how the value of the textarea, placed into an object, is filled with the wisdom of someone's boss:

<html>  <head>  <title> Text Area </title>  <script language="JavaScript">  function setUp( ) {       var TA=new Object( );        TA=document.memo.today;              TA.value="JavaScript can be used with a variety of applications and              designs. This message shall not be altered by the viewer on pain of a              nose snuffle. Just try it! \n Signed, \n The boss"        }  </script>  </head>  <body bgcolor="palegoldenrod">  <h3>Daily Memo:</h3>  <form name="memo"">        <textarea cols=40 rows=8 name="today" readonly=0></textarea><p>        <input type=button value="See Message" onClick="setUp( );"">  </form>  </body>  </html>
Hidden Text: Passing Unseen Data Between Pages

Hidden text boxes might not seem like too useful of a form element for designing web sites. However, hidden forms can be extremely useful when passing information between different pages in a frameset. To create a maze-like navigation system, used for anything from a cavern-and-tunnels adventure game to a problem-solving educational experience, knowing how to use JavaScript to simulate position is crucial.

The trick in any navigation system in which you have one driver page in a frame moving other pages left, right, forward, backward, or in any other combination of moves is to put the position information in the page that is being driven not in the driver page. In this way, each page that is moved "knows where it is." That is, relative to any direction, you can put the information in the page that is going to be moved in any direction.

The next question is, "Where do you put the information on a page so that another page can use it?" The answer to that is, "Put it in a hidden form element!" To access form information in one page from another page in a frameset, use the following format:

parent.frame.document.form.element.value 

Here, the element value is a URL. Then this statement will change the page in the frame to the value of the URL in the form element:

parent.frame.location = parent.frame.document.form.element.value 

By hiding the information in a hidden form on the page being moved, nothing is visible to get in the way of your design. This next script is a bit involved but really very simple illustration of how hidden forms can be used to pass along information in a circular movement of pages going to the left or right. A frameset and common CSS style aids in holding it all together.

First, the CSS has a common set of body background color, center text alignment, font, and font size. Each of the pages has a different color font to help identify the page. The driver page has a background color added to the font color to make it stand out a bit more.

hidden.css
body {       font-family:verdana;        font-size:16pt;        text-align:center;        background-color:ffdb18        }  .fontA {color:062456}  .fontB {color:f26d00}  .fontC {color:e43b24}  .fontD {color:188b57}  .fontDriver { color:e43b24;  background-color:062456  }

The frameset page is important for naming the frame of primary reference. In this frameset, the target frame is the one named info. By removing all borders, the page appears to be a single unified page rather than a frameset.

hiddenSet.html
<html>  <head>  <title>Cross Page Communication</title>  </head>  <frameset rows="*,*" border=0 framespacing=0 frameborder=0 >        <frame src="infoA.html" name="info" scrolling=no>        <frame src="driver.html" name="navigate" >  </frameset>  </html>

The next step is to create a page that will have the navigation buttons. By using "left" and "right" directions only, the task is simple and focuses on the whole concept of moving one page with another by taking information from the page that is moved. However, you could add any combination of moves, including vertical as well as horizontal movement. The point is to use the information on a page, send it to another page, and then move the page with the information. It would seem to be a lot easier just to put the buttons on the page being changed and click buttons on that page. That is certainly true, but you would be unable to have a single navigational page that would not blink every time a new page is loaded. By using a single navigation page, not only do you have less coding, but you also would have a page that would unblinkingly stay in place while the other pages move. (You always get a little blink when one page loads and another unloads.)

The functions that make all of this work are quite simple. The function to move left is as follows:

var left=parent.info.document.position.hereL.value;  parent.info.location=left; 

The function first places the hidden document element named hereL into a variable named left. Then the function uses the value of left, which now contains the URL for any left movement, and places it into the location of the frame that holds the page with the directional information. To see how this works, the following statement puts it into a single step using the array values instead of names:

parent.frames[0].location =  parent.frames[0].document.forms[0].elements[0].value; 

In other words, the driver page tells the other page to find out where it goes next by specifying where it should look in itself the hidden form elements. (Yoda would say, "The force is within you.")

driver.html
<html>  <head>  <link rel=stylesheet href="hidden.css">  <title>Driver</title>  <script language="Javascript">  function goLeft( ) {       var left=parent.info.document.position.hereL.value;        parent.info.location=left;        }  function goRight( ) {       var right=parent.info.document.position.hereR.value;        parent.info.location=right;        }  </script>  <body>  <div class=fontDriver>Click one of the buttons below</div>  <p>  <form name="direction">        <input type=button value="<=Left" onClick="goLeft( )">        <input type=button value="Right=>" onClick="goRight( )">  </form>  </body>  </html>

The final step is to have pages with the hidden forms. All four of the following pages are essentially the same, but each has a unique direction to go, depending on whether the left or right button is pressed in the driver page. If you wanted to have more directions, all you need to do is to add another hidden form with the information (URL) describing where to go.

infoA.html
<html>  <head>  <link rel=stylesheet href="hidden.css">  <title>InfoA</title>  <body><p>  <div class=fontA>  This is Page A<div>  <form name="position">        <input type=hidden name="hereL" value="infoB.html">        <input type=hidden name="hereR" value="infoD.html">  </form>  </body>  </html>
infoB.html
<html>  <head>  <link rel=stylesheet href="hidden.css">  <title>InfoB</title>  <body><p>  <div class=fontB>  This is Page B<div>  <form name="position">        <input type=hidden name="hereL" value="infoC.html">        <input type=hidden name="hereR" value="infoA.html">  </form>  </body>  </html>
infoC.html
<html>  <head>  <link rel=stylesheet href="hidden.css">  <title>InfoC</title>  <body><p>  <div class=fontC>  This is Page C<div>  <form name="position">        <input type=hidden name="hereL" value="infoD.htm">        <input type=hidden name="hereR" value="infoB.html">  </form>  </body>  </html>
infoD.html
<html>  <head>  <link rel=stylesheet href="hidden.css">  <title>InfoD</title>  <body><p>  <div class=fontD>  This is Page D<div>  <form name="position">        <input type=hidden name="hereL" value="infoA.html">        <input type=hidden name="hereR" value="infoC.html">  </form>  </body>  </html>

Figure 11.5 shows how the frameset appears when the user clicks his way to Page C.

Figure 11.5. The page in the bottom frame navigates the page in the top frame by using information in hidden forms in the top page.

graphics/11fig05.gif

Using hidden forms need not require assigning a value to the form. You can pass information to a hidden form just like you can a regular text box. However, in the previous example of using hidden forms, the purpose of the forms is to give information, not to receive it. For a very creative site, though, the information in the hidden forms could be dynamic, and, depending on circumstances in the context of the user clicking buttons, the information could change.

File Finder

Using file form elements is simple enough and can be useful in browsing files on local drives and disks. When you put in the tag <input type=file>, HTML automatically builds a Browse button and a text box. When the Browse button is clicked, an Open dialog box appears and you can select files from your own computer.

However, the purpose of the input text file form is to upload a file from the user's computer to a web server. In Chapter 16, "CGI and Perl ," you will see how to use CGI with input text files to upload files from your computer to a web server. The following simple utility to browse your drives and load a file shows you what the form generates:

<html>  <head>  <title>File Form</title>  <script language="Javascript">  function goGetIt( ) {       window.location= document.seek.browseMe.value;        }  </script>  <body>  <form name="seek">        <input type=file name="browseMe" size=40 ><P>        <input type=button value="Click here to load file." onClick="goGetIt( );">  </form>  </body>  </html>

Figure 11.6 shows you what you will see when you use the input text file form.

Figure 11.6. The input text file form allows you to browse your files and upload pages to a web server.

graphics/11fig06.gif

NOTE

Netscape Navigator 6 users see the entire path on their desktop to a file, even if opened in the same directory as the web page browsing.

Password Form

The final type of input text form to be examined is the password form. It works just like an input text form, but no alphanumeric characters appear when the user types in her password. Instead, the user sees black dots. However, whatever is typed in a password form can be compared with alphanumeric characters in JavaScript in the same way that any value that is in a text box can be. The following example shows one typical use of the input password form element:

<html>  <head>  <style type="text/css">  .blackPatch {       background-color:000000        }  </style>  <title>Password</title>  <script language="Javascript">  function checkIt( ) { var verify=document.pass.word.value;  if (verify=="JavaScript") {       alert("You may pass.")  } else {       alert("Sorry Jack, you\'re out of luck.")        }  }  </script>  <body>  <h3>Please enter your password and then  <br> click on the page out of the text box:</h3>  <div class=blackPatch>  <form name="pass">        some space <input type=password name="word" onBlur="checkIt( );"> more space  </form>  </div>  </body>  </html>

If you want to hide the password from anyone who knows how to use view source on his browser, you can put the function in an external JavaScript file and hide it someplace where it cannot be easily found and viewed (see Figure 11.7). (For serious hiding, you will need something more secure than an external .js file.)

Figure 11.7. The password input box shows no alphanumeric characters, but JavaScript can use the input in the same way as an uncoded text box.

graphics/11fig07.gif

Buttons and Their Events

Throughout the book, you have seen several examples of buttons. Usually, the buttons are employed to fire functions and sometimes forget that buttons are a form element instead of something else. The following are all of the HTML button elements to be discussed in this section:

  • <input type=button>

  • <input type=reset>

  • <input type=submit>

  • <input type=radio>

  • <input type=checkbox>

  • <input type=image>

The Generic Button

By this point in the book, you have probably seen most, if not all, of the attributes associated with the generic input button form. However, the following attributes are the most important to keep in mind:

  • name

  • value

  • Mouse events

    onClick

    onMouseOver

    onMouseMove

    onMouseDown

    onMouseUp

    onMouseOut

    onFocus

    onBlur

Usually, onFocus and onBlur are associated with input text; however, both event handlers work with the button as well. The following shows a simple example. (You will need NN6+ or IE5+ for this next script.)

<html>  <body>  <form >        <input type=button value="Blur Test" onBlur="alert('Blur works')">        <input type=button value="Focus Test" onFocus="alert('Focus works')">  </form>  </body>  </html>

Most importantly for the button is the fact that it can call upon an event to fire a JavaScript function. The value attribute actually does store a value in a button, and the value can be changed dynamically. However, for most applications, the button value is simply used to identify what the button does.

Clearing Forms with the Reset Button

In previous chapters, you have seen the Reset button used to clear forms. However, the Reset button has the same attributes as other buttons, in addition to clearing forms. You can simultaneously launch a function using a Reset button while clearing forms. Enter the following script and open it in a browser window. Type some text into the text box and then click the button.

<html>  <body>  <form>  <input type=reset value="Click to Launch" onClick="alert('Function launched')">  <input type=text>  </form>  </body>  </html>

Usually, the HTML that defines a Reset button is sufficient for most scripts; however, if the need arises to use the button to launch a function in addition to clearing the form, you can do so. The JavaScript reset( ) method emulates the button's action, and if the generic Reset button generated by HTML does not fit into your design, you may elect to do so. Also, you will want to use the button's value attribute to better clarify what the button does (such as Clear Form and Start Over).

The Submit Button

In the chapters on using the server-side scripts (beginning with Chapter 14), you will use the Submit button to call on scripts running on the server. For example, the following script segment shows the relationship between the Submit button and the <form> tag in launching a server-side script:

<form name="storage" method=get action="showStuff.php"> //Script on server to be launched  <input type=submit> //Effectively fires the action in the <form> tag. 

You can use a form.submit( ) script in JavaScript to launch a submit event and, design-wise, you might find it useful to do so. So, instead of having the generic Submit button generated by HTML, you can use any image or text style that you want as a button representation.

From the Submit button you can fire a simultaneous event in the <form> tag. Often used for form validation, data in the form will first be reviewed for accuracy before being sent to a database on a server. The onSubmit event handler activates when a Submit button belonging to the form is activated. For form validation using onSubmit, you need to write your JavaScript in relationship to a true or false outcome using the return keyword, as shown in the following simple script for form validation:

<html>  <head>  <title>Simple Validation</title>  <script language="JavaScript">  function CheckItOut(form) {       var yourName=document.folks.info.value;        if(yourName=="") {             alert("You know your name don\'t you? \n So type it in!");              return false;        } else {             alert("Thanks, " + yourName + " for sending in your name.");              return true;        }  }  </script>  </head>  <body>  <form name="folks" onSubmit="return CheckItOut(this)" >  Your Name Please:  <input type=text name="info"><p>  <input type=submit value="Click to Validate and Submit" >  </form>  </body>  </html>

When using a function that returns true or false and when setting up your onSubmit event to expect a return of some sort, a false return effectively cancels the submit. By creating a submit cancellation, the user is allowed to fill in those portions of the form not filled in at all or filled in incorrectly (such as a missing "@" in an email address).

Radio and Check Box Buttons

The radio and check box buttons can be evaluated as being checked or not a Boolean dichotomy. The key difference, and value, of the radio button is that only a single radio button with the same name can be checked. If you attempt to check more than one radio button with the same name, one already checked will pop to an unchecked position. With check box buttons, the user can check as many as she wants. Each button has three pertinent attributes:

  • name

  • checked

  • value

The general format inside a form container of each button is shown here:

<input type=radio name="radName" value="someValue" checked=Boolean>  <input type=checkbox name="checkName" value="someValue" checked=Boolean> 

To be useful, you need to include both the name and the value attributes. Optionally, you can have the checked attribute included as a Boolean value of true or false.

Both the checkbox and radio objects can be used to launch JavaScript functions. The onClick event handler can be added to either a checkbox or a radio tag.

Read the checked status of either the check box or radio button in JavaScript through the checked property of either objects. A generic JavaScript conditional statement examining the checked status of a radio button would read as follows:

if(document.form.radio.checked==true) {       var storage=document.form.radio.value  } 

The checked property works something like a value property, except that it has only Boolean values. Because the buttons both have a value attribute, the buttons also have a value property in JavaScript, as the previous generic statement shows.

This following script provides an example of using the two different types of buttons. The textarea in the example script shows the returns of the values in the checkbox and radio button tags.

radioCheck.html
<html>  <head>  <title>Checkboxes and Radio Buttons</title>  <style type="text/css">  body {       font-family:verdana;        font-size:11pt;        background-color:33ff66;        font-weight:bold  }  .fStyle {       color:595959;        background-color:b3ffcc;  }  </style>  <script language="JavaScript">  function sortItOut(form) {       var display="Key Feature and Components \n\n";        var reviewer =new Object( );        reviewer=document.hardware;        for (var counter=0; counter < reviewer.length; counter++) {       if(reviewer.elements[counter].checked) {             display += reviewer.elements[counter].value + "\n";              }        }        reviewer.showTime.value=display;  }  </script>  </head>  <body onLoad="document.hardware.reset( )">  <form name="hardware">        <div class="fStyle">Pick one of the following as the most important:<br>        <ul>        <input type=radio name="components" value="Cost" checked=true> Cost<br>        <input type=radio name="components" value="Reliability"> Reliability<br>        <input type=radio name="components" value="Reputation"        onClick="alert('Reputation?')"> Reputation<br>        <input type=radio name="components" value="Ease of Use"> Ease of use<p>  </ul>  Which of the following do you plan to purchase with your computer?  Check all that apply:<p>  <ul>        <input type=checkbox name="printer" value="Printer" > Printer<br>        <input type=checkbox name="disk" value="High Capacity Disk"> High Capacity Disk<br>        <input type=checkbox name="scan" value="Scanner" checked=true> Scanner<br>        <input type=checkbox name="mem" value="Additional Memory"> Added Memory<p></div>  </ul>        <textarea cols=50 rows=8 name="showTime"></textArea>        <input type=button value=" Sort It Out " onClick="sortItOut(this.form)">  </form>        </body>        </html>

When you run the script, you will notice that some of the boxes are already checked because they were set as checked in the HTML tags. However, as soon as you click on a check box that has a default checked status or on an unchecked radio button, it becomes unchecked. (See Figure 11.8.)

Figure 11.8. Both radio buttons and check boxes can pass values through JavaScript.

graphics/11fig08.gif

Image Form Elements

The input image is like a button object, except that the form element has a source image. The general format of the input image element is this:

<input type=image scr="imageURL" name="elementName"> 

The input image form works almost identically to using a graphic for links with the <a href...> tag. However, when using an input image element as part of a form, the element (object) is part of the forms object instead of the links object. Therefore, a reference to an input image object in JavaScript would be this:

document.formsName.elementName 

For designing web sites, having the capability to make your form buttons look like anything you want frees you from having to use the limited set of buttons built into HTML. The following script provides an example. (You will need to create a JPEG or GIF object named heart.jpg or heart.gif in the shape of a heart for a button.)

<html>  <head>  <style type="text/css">  body {       font-family:verdana;        font-size:11pt;        color:red;        background-color:#ffb7d0;        font-weight:bold;  </style>  <title>Image Form Element</title>  <script language="Javascript">  function lovesMe( ) {       var cupid=Math.random( );        cupid=Math.floor(cupid*100);        var throb="";        if (cupid > 50) {             throb="He loves me!"              //Change the gender pronoun to your preferences        } else {             throb="He loves me not...."              }        alert(throb);  }  </script>  <body>  <center>  <form name="heart">  Click the heart five times to learn how he feels about you! <p>        <input type=image src="heart.jpg" name="ache" onClick="lovesMe( );"         border=0><p>  If the answer is incorrect, click the button five more times....  </form>  </center>  </body>  </html>

Figure 11.9 shows the graphic button a heart-shaped graphic.

Figure 11.9. Image buttons allow for far greater design freedom.

graphics/11fig09.gif

You may include rollovers on your input image button elements. In the previous script, for example, the reference to the pertinent form object in JavaScript would be as follows:

document.heart.ache.src=newImage.src; 

In this way, the design can both contain a button that looks the way you want and has the liveliness of a rollover.

Menus

The last type of form element is the drop-down menu. The menu element in HTML is designed around three tags:

  • <select>

  • <select multiple>

  • <option>

The <select> or <select multiple> containers contain any number of options. In a similar manner to radio buttons and check box buttons, respectively, the <select> tag is mutually exclusive and the <select multiple> tag is not. So, if the user has only a single choice, use the <select> tag; if he has multiple choices, use <select multiple>.

Each <select> container is an array element of the forms object, and each <option> is an array element of the <select> container. For example, consider the following menu set up with the <select> container:

<form name="menu">        <select name="choose">              <option> Randy              <option> Judy              <option> Fred              </option>        </select>  </form> 

To reference the option Fred, the JavaScript array would read as follows:

document.forms[0].choose.options[2].text; 

Note that the select object must be referenced by its name (choose), not an element[ ] number in the forms[0] array. Also note that Fred is a string literal in the text property, not the value property. The value property when dealing with select and option objects is the value assigned with in the <option> tag, such as this:

<option name="chooseMe" value="eternal wisdom"> Comedy

The following JavaScript statement would put the string literal eternal wisdom in the variable named stuff, assuming that the second option was Comedy:

var stuff = document.formName.selectName.options[1].value; 

Most form elements in HTML have a value in the JavaScript object that reflects the corresponding HTML element. However, with the select object, the key value is called selectedIndex, reflecting which of the options the user selects. The selectedIndex keyword returns an array value for the options element. For example, consider the following HTML script and JavaScript reference to what is selected.

HTML
<form name="iceCream">        <select name="flavors">              <option> Chocolate              <option> Strawberry              <option> Vanilla  </option> </select></form>
JavaScript
var getChoice = document.iceCream.flavors;  var youChose = getChoice.options[getChoice.selectedIndex].text;

For example, if the user chooses Strawberry, the selectedIndex would return 1 because the second option is recognized as options[1]. Look at the following example to see what's going on under the hood in the page using a menu:

<html>  <head>  <title>Menu Form</title>  <script language="Javascript">  function getFlavor( ) {       var scoop = document.iceCream.flavors;        var cone = scoop.options[scoop.selectedIndex].text;        if(cone !="Flavor Menu") {             alert("Here\'s your " + cone + " ice cream cone!")        }  }  </script>  <body onLoad="document.iceCream.reset( );">  <form name="iceCream">  <h3> Select your flavor from the menu:</h3>        <select name="flavors" onChange = "getFlavor( )">              <option name="dummy" value=null>Flavor Menu              <option >Peach              <option >Peppermint              <option> Rasberry Swirl              <option> Rum Raisin              </option>        </select><p>  </form>  </body>  </html>

The first option text is Flavor Menu. This text is added because, without it, you cannot effectively use the onChange event handler to select the choice at the top of the menu. Essentially, the option is a dummy one that allows a label inside the menu.

If you use the <select multiple> tag, the viewer can see all of the selection options at once. If you have room on your web page, using <select multiple> is usually easier for the user because she doesn't have to hold open the menu while making a choice. However, your own design considerations outweigh utility in this case. In the previous example script using <select>, change the tag to <select multiple> and run the script in your browser again.

Summary

Forms are one of the most important elements in HTML and JavaScript. With forms, the web designer can engage the viewer, provide feedback, and move information to different locations. The window boxes and buttons are both sources of data entered by the user and events that can be dynamically used in a page design. For purposes of discussing forms with design, they were categorized into text, buttons, and menu types of forms. Each of these form elements is further broken down into the different components. However, as JavaScript objects, most appear very much the same.

Menu forms are a bit different, but, when working with forms in JavaScript, each element still is a property of the document and the form. In turn, the attributes of the different types of form elements are properties, and all line up in similar JavaScript fashion as objects that can be used in very creative ways.

In the third section of this book, beginning with Chapter 14, forms are the doorway between HTML and server-side scripts and data. JavaScript is the doorkeeper for user-entered data and serves to verify data before passing it along to the back end. All of the data passed through the JavaScript filer, though, first appears in forms in some manner. So, while the next two chapters only marginally rely on JavaScript working with forms, subsequent chapters have a central role for forms and JavaScript.

CONTENTS


JavaScript Design
JavaScript Design
ISBN: 0735711674
EAN: 2147483647
Year: 2001
Pages: 25

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net