Real newbie stuff this, but how do you get the currently selected <option>
of a <select>
element via JavaScript?
views:
59answers:
2
+2
A:
The .selectedIndex
of the select
object has an index; you can use that to index into the .options
array.
Amber
2010-07-21 16:45:05
+4
A:
This will do it for you:
var yourSelect = document.getElementById('your-select-id');
alert(yourSelect.options[yourSelect.selectedIndex].value)
Pat
2010-07-21 16:46:16
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
2010-07-21 16:52:03
@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
2010-07-21 17:02:54
@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
2010-07-29 16:24:33