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.



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

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

* text in lieu of value
The Firefox and Mozilla versions I listed support this, but the other browsers I tested don't.


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;


		<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>
		<input type="button" value="Show Index" onclick="showSelected();" />
		<input type="text" id="txtIndex" />
		<br />
		<input type="text" id="txtValue" />
		<br />
		<input type="text" id="txtText" />
		<br />

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)

About this page: