views:

59

answers:

2

Real newbie stuff this, but how do you get the currently selected <option> of a <select> element via JavaScript?

+2  A: 

The .selectedIndex of the select object has an index; you can use that to index into the .options array.

Amber
+4  A: 

This will do it for you:

var yourSelect = document.getElementById('your-select-id');
alert(yourSelect.options[yourSelect.selectedIndex].value)
Pat
if you use it to access the value of the option, you may as well just use `yourSelect.value`. Very old, archaic browsers might not support it, but IE6 and every modern browser does.
Andy E
@Andy E: ooh, there’s an idea — that is indeed what I’m doing, and your code is a bit easier to read.
Paul D. Waite
@Andy E: ah, one caveat about that method — it doesn’t return the text of the `<option>` element in IE, I think you need to have something in the `value` attribute.
Paul D. Waite