Section 7.3. Selection


7.3. Selection

The select element and its associated options provide a way to choose one or more items from a list. It's defined using the following syntax:

<select name="theSelection" multiple> <option value="Opt1">Option 1</option> <option value="Opt2">Option 2</option> ... <option value="Optn">Option n</option> </select>

The select element has the following properties that are accessible from JavaScript:


disabled

Whether the element is disabled


form

The containing form


length

Number of options in options array


options

Array of options


selectedIndex

For single select, number of item selected; for multiple, first item selected


type

Type of element

The select options are included in the options array. Each of these are objects, themselves with several properties. However, for forms validation, the properties of interest are selected, value, and text. The selected property is set to true if the option is selected; the option value is given in value, and the text that's visible to the web-page reader is given in text.

There are two ways to get the selected options from a selection, depending on whether multiple options can be selected or only one. If only one option can be selected at a time, using the select property of selectedIndex on the options array returns the selected object:

var slIdx= document.formname.theSelection.selectedIndex; var opt = document.formname.theSelection.options[slIdx];

If multiple options can be selected, the code needs to iterate through the entire options array and check which options are selected. In Example 7-1, a multiple selection list is created with three options. When the form is submitted, the option text and value for each selected option is printed out in the pop-up window.

Example 7-1. Processing the results of a multiple-selection list

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Input form</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> //<![CDATA[ if (window.addEventListener) {       window.addEventListener("load",setupEvents,false);    } else if (window.attachEvent) {       window.attachEvent("onload", setupEvents);    } else {       window.onload=setupEvents; } function setupEvents(evnt) {    document.someForm.onsubmit=checkForm;  } function checkForm(evnt) {    var opts = document.someForm.selectOpts.options;    for (var i = 0; i < opts.length; i++) {       if (opts[i].selected) {          alert(opts[i].text + " " + opts[i].value);       }    }    // no server side processing, cancel submit event    return false; } //]]> </script> </head> <body> <form name="someForm"> <select name="selectOpts" multiple> <option value="Opt1">Option One</option> <option value="Opt2">Option Two</option> <option value="Opt3">Option Three</option> </select> <input type="submit" value="Submit" /> </form> </body> </html> 

Selection lists are normally used when you have a larger number of optionssuch as a list of states in the U.S. or cities in China. As such, you'll most likely want to limit your selection to one entry so that you can specifically access the option using selectedIndex, rather than have to iterate over a larger array. Still, the time to run through an array is short; the number of options picked is up to you.

You can also dynamically build a selection list based on real-time events.

In Example 7-1, DOM Level 2 event handling is used for the window load event, but traditional DOM Level 0 is used for the form submittal. Most of the examples in the rest of the book use the older event model because it's easier to implement, requires less code, and allows us to focus on those aspects of JavaScript currently being demonstrated. Example 7-3 provides a demonstration of DOM Level 2 for all functions.

For the most part, though, you'll want to use the newer event handling as much as possibleespecially if you're using external libraries, as discussed in Chapter 14.


7.3.1. Dynamically Modifying the Selection

Using JavaScript, you can create and remove selection list items on the fly, perhaps based on some other user input. To add a new option in the code shown in Example 4-9, create a new Option element and add it to the options array:

   opts[opts.length] = new Option("Option Four", "Opt 4");

Since arrays are zero-based, adding a new array element at the end can always be accomplished by using the array's length property as the index.

To remove an option, just set the option enTRy in the array to null. This resets the array so there is no gap in the numbering:

opts[2] = null; 

To remove all options, set the array length to zero (0):

opts.length = 0;  

It's not unusual to modify a selection list based on the answers given in other form elementsespecially if you're using a drop-down listbox, in which the options don't show until the user clicks the arrow to open the list. Note, though, that the box may resize horizontally depending on the length of each option.

7.3.2. Selection and JiT Validation

In addition to processing the array elements during a form submit, you can capture when a change is made to the selection and perform instant or JiT validation. This is accomplished by capturing a change event for the form field, testing the value of the field, and then providing immediate feedback. This can be a lot less frustrating to the people filling out the forms; they won't have to wait until all the fields are filled in to validate the whole form.

I modified the code in Example 7-1 to create an example of JiT validation. In Example 7-2, two options are nested with two others so that if you select the parent option, you'll automatically get the nested option; however, the converse is not trueselecting the nested option does not give you the parent.

Example 7-2. Using JiT with a selection

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Input form</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> //<![CDATA[ if (window.addEventListener) {       window.addEventListener("load",setupEventsl,false);    } else if (window.attachEvent) {       window.attachEvent("onload", setupEvents);    } else {       window.onload=setupEvents; } function setupEvents(evnt) {    document.someForm.selectOpts.onchange = checkSelect; } function checkSelect(evnt) {        var opts = document.someForm.selectOpts.options;    for (var i = 0; i < opts.length; i++) {       if (opts[i].selected) {           switch(opts[i].value) {             case "Opt1" : opts[i + 1].selected = true;                           break;             case "Opt3" : opts[i + 1].selected = true;                           break;             case "Opt4" : opts[i + 1].selected = true;                           break;           }       }    }    // no server side processing, cancel submit event    return false; } //]]> </script> </head> <body> <form name="someForm"> <select name="selectOpts" multiple> <option value="Opt1">Option One</option> <option value="Opt1a"> -- Option OneA</option> <option value="Opt2">Option Two</option> <option value="Opt3">Option Three</option> <option value="Opt3a"> -- Option ThreeA</option> <option value="Opt4">Option Four</option> <option value="Opt4a"> -- Option FourA</option> <option value="Opt5">Option Five</option> </select> <input type="submit" value="Submit" /> </form> </body> </html>

Having some options automatically selected can ensure the accuracy of the data. It's also rather impressive-looking without requiring a lot of effort.

How often you use JiT validation depends on the complexity of your form and the purpose for the form. Using JiT for every form element could irritate rather than help, but waiting to validate and providing a long list of needed changes could overwhelm. As always, the code can only do so much; you'll need to use your own judgment as to how and when to use it.




Learning JavaScript
Learning JavaScript, 2nd Edition
ISBN: 0596521871
EAN: 2147483647
Year: 2006
Pages: 151

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