<%response.buffer=true%> <% yere = year(date()) Response.Expires = 0 %> Advanced Forms
<forms>
  spacerspacer

Advanced Forms

Checking Other Form Elements: While it is easy to check textboxes and textareas for some type of input by checking the value property, it is different for other types of form elements. Radio buttons and checkboxes usually have a value (what the user chooses by clicking the element) so we need to see if the user has "checked" that item with JavaScript.

Grouping Radio Buttons & Checkboxes: For radio buttons (or checkboxes) to operate together, each button to be included must have the same name. When more than one radio button has the same name, we will call them a "group":

Favorite Color:

Red: <input type="radio" name="FavoriteColor" value="red" /><br />
Blue: <input type="radio" name="FavoriteColor" value="blue" /><br />

Yellow: <input type="radio" name="FavoriteColor" value="yellow" /><br />

Once the buttons are grouped, each button is an element of an array that can be called by the group's name. We can determine which radio button of a group is currently checked by looping through the button array:

for (var x=0; x<document.myForm.FavoriteColor.length; x++){
    if (document.myForm.FavoriteColor[x].checked){
        alert("Aha! You are a " + document.myForm.FavoriteColor[x].value);
    }
}

An easy way to validate a radio button group is to check to see if any value is assigned to a variable while looping through the values. If no value is assigned to the variable after a complete loop, (it would contain null) then no item was checked:

for (var x=0; x<document.myForm.FavoriteColor.length; x++){
    if (document.myForm.FavoriteColor[x].checked){
    var myTest = document.myForm.FavoriteColor[x].value;       
    alert("Your favorite color is " + document.myForm.FavoriteColor[x].value);
    }
}

if(myTest == null){
    alert("You didn't select a color!");
}

For form validation purposes, we can deal with checkboxes in the same manner as radio buttons. Here is an example form that demonstrates the code above: Which Color

Checking All Checkboxes: With checkboxes we can allow a user to select multiple items. Sometimes we want to allow users to check or uncheck all checkboxes on a form at once. This is common if you are going to delete multiple items, or send emails to users, etc.

To do this, you can choose one checkbox to be the toggle. As the "toggle" the state of that checkbox, when checked or unchecked, will cascade to all applicable checkboxes on the form:

function toggle(myCheck){
    for(var x=0; x<myCheck.length; x++){
    myCheck[x].checked = document.myForm.checkAll.checked;
    }
}

The "toggle" function is called everytime the checkbox named "checkAll" is checked. The onChange event of the checkbox is used to trigger the function:

Check/Uncheck all:<input type="checkbox" name="checkAll" onclick="toggle(document.myForm.myEmail);">

Here is an example: Toggle Email

Select Options: Select option form elements are handled in a different manner. The individual options inside a select are accessed as an array, in a similar manner to a radio button. We can loop through the select array to see which item is currently selected. Here is a JavaScript snippet that loops through a select object that contains various states:

for (var x=0; x<document.myForm.myState.length; x++){
  if (document.myForm.myState.options[x].selected){
    var myTest = document.myForm.myState.options[x].value;
    alert("Aha! You're from " + myTest);
  }
}

To check to see if at least one item is selected, however, it is not as easy as with a radio button. Since a select option normally has the first item in the array "selected" by default (if no other option is chosen) we must avoid the first item in the array. Note this example select object:

<select name="myState">
<option value="CA">California</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>
</select>

In the above example, California is the first item in the select array (with an index of zero). Since it is the first element in the array (the first option) it will automatically show as selected, unless we specify otherwise! It is the nature of the select to have at least one item selected! Since we routinely want the user to make their own selection, we'll amend the select object:

<select name="myState">
<option value="">Select A State</option>
<option value="CA">California</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>
</select>

Now we have a "label" inserted into the zero array element (first element) of the select object! This is to instruct the user to choose a different option, and to give us a "default" that indicates no option has yet been selected! Now to see that a user has entered some choice in the select element, we can simply test for the first element in the array. Any OTHER choice would be acceptable:

if(document.myForm.myState.options[0].selected == true){alert("Please select a state!");}

To work with the value of the selected option, we can use the "selectedIndex" property. This gives us the first selected option in a select object. We can get the currently selected value out of the select option with one long line of code:

var myState = document.myForm.myState.options[document.myForm.myState.options.selectedIndex].value;

If we pass the "myState" select object into the function, we can shorten this code considerably:

function checkState(myState){
    var myState = myState.options[myState.options.selectedIndex].value;
    alert("Your state is " + myState);
}

Here is an example that demonstrates the select object: Which State

Checking Multiple Element Types: On our basic forms page we checked text boxes for data entry. We later showed how checkboxes, radio buttons and select options need a different strategy. View the following example for how to check for required form data by adding a single letter to the name of the element: checkReq

Validating Complex Forms: When we work with forms we benefit from starting with a form that has some validation already present in it.  The third version of the JS template adds form validation functions such as empty() which checks a set of radio buttons, checkboxes, a select or text type form elements for required selection. It requires some sort of data entry (any string data, any type) of input elements (text,password) or textarea elements: js_template3.htm

Get the code here: JS Template Version 3 Zip File

Miscellaneous Form Tricks

Processing User Input: The following example attempts to "normalize" (format) inconsistently "cased" data as entered by a user. There are 3 custom functions on this page. The most critical of them is called "capFirst", which is designed to take any string of data, and capitalize the first letter of each word, set to lower case the rest of the word and rebuild the string, and return the string out of the function: capFirst

The Select Object As Navigation: The select object is also used to navigate between web pages. We can access the "onChange" event handler to load a new web page when a the user selects an option. Here is a small form that includes one select object:

<form name="myNav">
<select name="myList" onChange="jumpTo(myList)">
<option value="#">Click N Go!</option>
<option value="http://www.google.com">Go To Google</option>
<option value="http://www.yahoo.com">Go To Yahoo</option>
</select>
</form>

There is no submit button on this form, because there is a function named "jumpTo" which is called when the option selected is changed. The entire select object, named "myList" is sent to a function:

function jumpTo(list){
  var myLink = list.options[list.selectedIndex].value;
  if(list.selectedIndex != 0){
    location.href= myLink;
  }
}

Once the select object (now named "list") is sent to the function, the selected value is determined, and if the index is not zero, the location object is used to change the web address! (Send the user to a different page).

Remember that the "zero" index in this case would be the label "Click N Go!". Since this is the default, we don't want to use this for navigation, as the user would need to CHANGE the current selection (using the onChange event)! Click N Go

Submit Only Once: Sometimes users get impatient and click the "submit" button on a form about a dozen times, wreaking havoc on the database. We can stop the user from doing this by substituting a "button" type form element for the "submit" button, and then disabling the button after one click:

<input type="button" value="Submit, only once!" onclick="this.disabled.true; this.form.submit()" />

A better version would use a custom function that would check for valid data, and then submit the form.

Limit Textarea Characters : Textareas do not have the "maxlength" property, until you add your own! This trick relies on adding a "maxlength" attribute to a textarea object, then wiring a function to the "onKeyPress" event which checks for the total number of characters in the Textarea each time a character is added:

<textarea rows="5" name="complaints" cols="20" maxlength="10" onkeypress="return maxLength(this)"></textarea>

The result of the check is only returned if the maxlength is less than the artificial attribute:

function maxLength(myText) {
    return myText.value.length != myText.getAttribute("maxlength");
}

Try the example: maxLength

Dynamic Link Submittal: You can use a link to submit a hidden form, and can even change values in a hidden field based on the link selected by the user! This is handy for dynamically generating multiple links on a page (out of a database) while still submitting the page via POST instead of GET!! First, create a form with a hidden field (or fields) and no submit button:

<form name="myForm" action="myFormHandler.php" method="post">
<input type="hidden" name="customer" value="John Doe" />
<input type="hidden" name="customerID" value="12345" />
<input type="hidden" name="toy" value="default ducky" />
</form>

Next, build a function that accepts three parameters; the name of the hidden form, the name of the hidden form field to change the value on, and the value to change it to:

function hideSubmit(thisForm,thisElement,myVal){
    thisElement.value = myVal;
    thisForm.submit();

}

Now we can load a JS function into the "onClick" event handler of each involved link:

<a href="javascript(void);" onclick="hideSubmit(myForm,myForm.toy,'froggy');">Click for a Froggy!</a>

See how this works: hideSubmit

 

   
Print this Page Back To Top

2000- <%=yere%> newMANIC INC, All rights reserved