Validating Selection Lists


if (f.elements["colors"].selectedIndex == -1) {   window.alert("No color selected!");   f.elements["colors"].focus();   return false; } else {   return true; } 

There are several ways to validate a selection list. The easiest one is to check the selectedIndex property. If its value is -1, no item has been selected, and therefore the form has not been filled out sufficiently. The preceding code demonstrates this (full version in file mandatory-list.html).

However, this approach works only when the selection list has its size attribute set to a value greater than one and does not contain any empty elements (for demonstration purposes). A better way to validate a list is to look at the value attributes of all selected elements. If the value is an empty string, the element is not taken into consideration. A for loop iterates over all elements in the list and looks for selected elements with an actual value. This approach has the additional advantage that it also works with multiple selection lists.

Validating a Selection List (mandatory-list-loop.html)

<script language="JavaScript"   type="text/javascript"> function checkform(f) {   for (var i=0; i<f.elements["colors"].options.length; i++) {     var element = f.elements["colors"].options[i];     if (element.selected && element.value != "") {       return true;     }   }   window.alert("No color selected!");   f.elements["colors"].focus();   return false; } </script> <form onsubmit="return checkform(this);">   <select name="colors" size="9"     multiple="multiple">     <option value="">Select a color</option>     <option value="R">red</option>     <option value="G">green</option>     <option value="B">blue</option>     <option value="">-</option>     <option value="C">cyan</option>     <option value="M">magenta</option>     <option value="Y">yellow</option>     <option value="K">black</option>   </select>   <input type="submit" value="Submit data" /> </form> 

As you can see from Figure 8.7, the two filler elements do not count.

Figure 8.7. The form may be submitted only if a "real" element has been selected.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

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