JavaScript can be used to retrieve what the currently selected item is in a dropdown select list.
If a select list is defined as follows:
select name='colors' id='colorsselect'
An often-seen method to retrieve the value of the selected item:
var dropdownIndex = document.getElementById('colorsselect').selectedIndex;
var dropdownValue = document.getElementById('colorsselect')[dropdownIndex].value;
document.write(dropdownValue);
The preceding example uses the selectedIndex property of the dropdown box to return the index of the selected item, with the first item in the list being 0, the second being 1 and so forth. Once the selectedIndex is retrieved, the select box values are referenced as an array. The element retrieved is the element existing in the selectedIndex position.
An easier implementation to retrieve the value of a dropdown select list is to just access the select list’s value property directly:
document.write(document.getElementById('colorsselect').value);
Related Articles:
JavaScript selectedIndex property
Accessing Form Elements with JavaScript