How do you get the currently selected <option> of a <select> element via JavaScript?
5 Answers
This will do it for you:
var yourSelect = document.getElementById( "your-select-id" ); alert( yourSelect.options[ yourSelect.selectedIndex ].value ) 3 Comments
Andy E
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.Paul D. Waite
@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.The .selectedIndex of the select object has an index; you can use that to index into the .options array.
1 Comment
Rice
This is the most elegant and straightforward approach
Using the selectedOptions property:
var yourSelect = document.getElementById("your-select-id"); alert(yourSelect.selectedOptions[0].value); It works in all browsers except Internet Explorer.
2 Comments
Paul D. Waite
“It works in all browsers except Internet Explorer.” As soon as everyone stops using Internet Explorer, we’re golden! Possible polyfill here.
if you don't have multiple selection You can do it like.
var yourSelect = document.getElementById( "your-select-id" ); alert(yourSelect.selectedOptions[0].value) Will do the same thing like the choosen answer. Since .selectedOptions gives you a list of selected options elements
1 Comment
Paul D. Waite
Sure, although it's already mentioned in this answer
<option>.