HTML/JavaScript - Working with selectedIndex
select, options, selectedIndex, text, value
Try It
Choose an item in the select (a.k.a. drop down) and click Show Index. The results will display in the text boxes.
Overview
The selectedIndex number can be used to reference the selected option in the select list. Note: It is case sensitive. Make sure to capitalize the "I" in selectedIndex
- selectedIndex - The number (base 0) of the item that is selected in the select list
-
value - For an option, what's in the value attribute.
If the value attribute is not set, text should be returned [* refer below] - val1 is the value in the following HTML example
- <option value="val1">sea one</option>
- text - For an option, what's in between the option tags
- sea two is the text in the following HTML example
- <option value="val2">sea two</option>
Browser Support
selectedIndex is supported in practically any browser. However the example on this page uses getElementById, so it will only work in browsers that support DOM Level 2. The Try It example has been tested and works in Firefox 0.9.1+, Mozilla 1.7.1, Netscape 6.1, and Internet Explorer 6.0.
One way to reference selectedIndex in an older browser
is to name your HTML elements (using the name attribute)
and make absolute references to the objects.
e.g. If the form is named frmName and the select is named selName
document.frmName.selName.selectedIndex
* text in lieu of value
The Firefox and Mozilla versions I listed support this,
but the other browsers I tested don't.
Source
Public Domain
The HTML and JavaScript listed below are released to the public domain. Read the Terms of Use for details. The contents of this page are still copyrighted.
The JavaScript
<script language="JavaScript" type="text/javascript"> <!-- function showSelected() { var selObj = document.getElementById('selSeaShells'); var txtIndexObj = document.getElementById('txtIndex'); var txtValueObj = document.getElementById('txtValue'); var txtTextObj = document.getElementById('txtText'); var selIndex = selObj.selectedIndex; txtIndexObj.value = selIndex; txtValueObj.value = selObj.options[selIndex].value; txtTextObj.value = selObj.options[selIndex].text; } //--> </script>
The HTML
<form> <p> <select id="selSeaShells"> <option value="val0">sea zero</option> <option value="val1">sea one</option> <option value="val2">sea two</option> <option value="val3">sea three</option> <option value="val4">sea four</option> </select> <input type="button" value="Show Index" onclick="showSelected();" /> </p> <p> <input type="text" id="txtIndex" /> selectedIndex <br /> <input type="text" id="txtValue" /> options[].value <br /> <input type="text" id="txtText" /> options[].text <br /> </p> </form>
Supplemental Information
(external links - open in new window)
selectedIndex (W3C - DOM Level 1)
text (W3C - DOM Level 1)
value (W3C - DOM Level 1)
getElementById (W3C - DOM Level 2)