Accessing a Multiple Selection List


s += "Element #" + i   + " (" + option.text   + "/" + option.value   + ") " + (option.selected ?     "selected." : "not selected.")   + "\n"; 

When an HTML selection list gets the multiple="multiple" attribute, more than one element can be selected. In this case, the selectedIndex property does not help very much since it only informs about the first selected element in the list, not all. Therefore, a for loop should be used to iterate over all list elements. When the selected property is TRue, the list item is selected.

The following code outputs information about all list elements, including whether or not they are selected:

Accessing a Multiple Selection List (selectionlistmultiple.html)

<script language="JavaScript"   type="text/javascript"> function showStatus(f) {   var s = "";   var list = f.elements["selectionlist"];   for (var i=0; i<list.options.length; i++) {     var option = list.options[i];     s += "Element #" + i       + " (" + option.text       + "/" + option.value       + ") " + (option.selected ?         "selected." : "not selected.")       + "\n";   }   window.alert(s); } </script> <form>   <select name="selectionlist" size="3"     multiple="multiple">     <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> 

In Figure 8.2 you can see the result when a few of the elements are selected, but not all.

Figure 8.2. Some elements are selected.


File Uploads and JavaScript

With JavaScript it is also possible to access file upload HTML elements (<input type="file" />). However, in the past few years, web browser developers have restricted the JavaScript access to these kinds of form fields more and more. And there is good reason for that, too. Imagine a hostile JavaScript code that sets the value of the file upload field to, say, /etc/passwd and then automatically submits the form. Therefore, this is usually not possible any more. Also, some browsers print out a message whenever files will be uploaded alongside a form (see Figure 8.3). Therefore, you should avoid controlling form upload fields with JavaScript; with basic HTML and a server-side technology, they do work fine.

Figure 8.3. Konqueror warns about files being sent with the form.






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