Accessing Selection Lists


var index = f.elements["selectionlist"].selectedIndex; 

An HTML selection list consists of two elements: <select> lays the foundation and provides the name of the whole list (in its name attribute). The actual list elements are represented by <option> elements and provide two things: a caption (the data shown in the browser) and the value (the data sent to the server when the form is submitted).

When you're working with JavaScript, two ways of accessing the list data are available:

  • selectedIndex provides the index (starting at 0) of the currently selected list element; a value of -1 means that no value has been selected (applicable only for lists with size greater than 1).

  • options is an array with all list options. Every option supports the selected property. When true, the list option is selected.

Usually, selectedIndex is good enough for validation purposes. The options approach comes in quite handy when the selected list element will be accessed, as well. Then, the value attribute of the selected option provides the data sent to the server, and the text property returns the caption visible in the browser.

The following listing accesses all important information regarding the selected option:

Accessing a Selection List (selectionlist.html)

<script language="JavaScript"   type="text/javascript"> function showStatus(f) {   var index = f.elements["selectionlist"].selectedIndex;   if (index == -1) {     window.alert("No element selected");   } else {     var element = f.elements["selectionlist"].options[index];     window.alert("Element #" + index +       " (caption: " + element.text +       ", value: " + element.value +       ") selected");   } } </script> <form>   <select name="selectionlist" size="3">     <option value="R">red</option>     <option value="G">green</option>     <option value="B">blue</option>   </select>   <input type="button" value="Show status"     onclick="showStatus(this.form);" /> </form> 

Note

Recent browsers also support the following shortcut for accessing the value of the currently selected list element:

f.elements["selectionlist"].value 


However, to maintain maximum browser compatibility, the following approach requires a bit more typing, but also works on older software:

f.elements["selectionlist"].options[   f.elements["selectionlist"].selectedIndex].value 






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