How do you get the currently selected <option> of a <select> element via JavaScript?
Asked
Active
Viewed 1.2e+01k times
67
ROMANIA_engineer
- 51,252
- 26
- 196
- 186
Paul D. Waite
- 93,468
- 54
- 192
- 264
-
1Possible duplicate: [How to get the selected value of dropdownlist using JavaScript?](http://stackoverflow.com/questions/1085801/how-to-get-the-selected-value-of-dropdownlist-using-javascript) – Anderson Green May 26 '13 at 07:33
-
2@AndersonGreen: that isn’t *quite* the same question. It’s actually asking how to get the text of the selection ` – Paul D. Waite May 26 '13 at 08:49
4 Answers
113
This will do it for you:
var yourSelect = document.getElementById( "your-select-id" );
alert( yourSelect.options[ yourSelect.selectedIndex ].value )
Pat
- 24,658
- 6
- 71
- 67
-
12if 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 Jul 21 '10 at 16:52
-
@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 Jul 21 '10 at 17:02
-
@Andy E: ah, one caveat about that method — it doesn’t return the text of the ` – Paul D. Waite Jul 29 '10 at 16:24
25
The .selectedIndex of the select object has an index; you can use that to index into the .options array.
4
var payeeCountry = document.getElementById( "payeeCountry" );
alert( payeeCountry.options[ payeeCountry.selectedIndex ].value );
-
Your answer has been marked 'low quality' on account of its length and content. May I suggest that you make it a comment to the question? – Bill Bell Nov 21 '16 at 15:45
2
Using the selectedOptions property:
var yourSelect = document.getElementById("your-select-id");
alert(yourSelect.selectedOptions[0].value);
It works in all browsers except Internet Explorer.
Finesse
- 8,378
- 7
- 57
- 72
-
2“It works in all browsers except Internet Explorer.” As soon as everyone stops using Internet Explorer, we’re golden! [Possible polyfill here](https://gist.github.com/brettz9/4212217). – Paul D. Waite Jan 31 '18 at 08:42