First, let us establish a sample select object as below. The Javascript object “objSelect” will also be established to refer to this HTML object.
The following Javascript code can be used to display which option has been selected by the user. If you choose “Blue”, for example, you will get alert dialogues “b”, “Blue”, and then “2”.
alert(objColors.value); // Display the value; in this example, red is "r", green is "g", and blue is "b" alert(objColors.options[objColors.selectedIndex].text); // Display the text; in this example, "red", "green", and "blue" alert(objColors.selectedIndex); // Display the index number; in this example, red is 0, green is 1, and blue is 2
The following Javascript code provides you the means to add a new option to the HTML select object. “Yellow” is going to be added to the end of the list, and “White” is going to be added as the third choice.
var newOption1 = document.createElement('option'); newOption1.text = "Yellow"; newOption1.value = "y"; var newOption2 = document.createElement('option'); newOption2.text = "White"; newOption2.value = "w"; try { // For standard browsers objColors.add(newOption1, null); } catch (ex) { // For Microsoft Internet Explorer and other non-standard browsers. objColors.add(newOption1); } try { // For standard browsers objColors.add(newOption2, objColors.options[2]); } catch (ex) { // For Microsoft Internet Explorer and other non-standard browsers. objColors.add(newOption2, 1); }
The code below removes an option. The first example removes index #1, or the second option. The second example removes whatever the last option is.
objColors.remove(1); // Removes index #1, or "Green" in our original example. objColors.remove(objColors.length-1); // Removes whatever the last option is.
Finally, the code below selects a particular option.
<
pre class="code">
objColors.options[1].selected = true; // Selects the second option, or “Green” in our original example
You may see the running examples below.
Complete code to the running examples is shown below.