18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>For</strong>ms and Data Integrity<br />

Because both controls use the same HTML code, it’s possible to manipulate them using the same<br />

<strong>JavaScript</strong> code. Naturally, the first step to manipulating either is to get a reference from the document<br />

either by using document.getElementById() or accessing it in the document.forms collection:<br />

oListbox = document.getElementById(“selAge”);<br />

oListbox = document.forms[“form1”].selAge;<br />

oListbox = document.forms[0].selAge;<br />

<strong>For</strong> this section, the methods you create are all attached to a common object called ListUtil, in order to<br />

keep them straight (similar to the EventUtil object created earlier in the book). ListUtil is just a simple<br />

object to which the methods are attached:<br />

var ListUtil = new Object();<br />

Accessing options<br />

The HTML DOM defines each element to have a collection called options, which is the list<br />

of all elements for the control. To get the display text and value of an , you can<br />

use normal DOM functionality:<br />

alert(oListbox.options[1].firstChild.nodeValue);<br />

alert(oListbox.options[1].getAttribute(“value”));<br />

//output display text<br />

//output value<br />

However, it is easier to use two special properties that are defined in the HTML DOM: text,<br />

which returns the display text, and value, which returns the value attribute. These two properties are<br />

provided for backwards compatibility with older BOM functionality used to manipulate options.<br />

alert(oListbox.options[1].text);<br />

alert(oListbox.options[1].value);<br />

//output display text<br />

//output value<br />

Each also has an index property, indicating its position in the options collection:<br />

alert(oListbox.options[1].index); //outputs “1”<br />

Of course, because options is a collection, you can use its length property to determine how many<br />

options exist:<br />

alert(“There are “ + oListbox.options.length + “ in the list.”);<br />

But how do you know which option is currently selected?<br />

Retrieving/changing the selected option(s)<br />

The element has an attribute, selectedIndex, which always contains the index of the currently<br />

selected option (or –1 if no options are selected).<br />

alert(“The index of the selected option is “ + oListbox.selectedIndex);<br />

357

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!