Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value of <select> the modern way?

Tags:

javascript

I was under the impression that in order to get the value from <select> you essentially had to do this:

var sel = document.getElementById("my-select");
var val = sel.options[sel.selectedIndex].value;

But I ran into some code today that simply does document.getElementById('my-select').value, which seems to work perfectly fine in Chrome and Firefox.

Has this changed recently, or has it always been this way? How far back is this supported?

like image 829
mpen Avatar asked Apr 30 '13 15:04

mpen


People also ask

How do I get selected value in select?

Answer: Use the jQuery :selected Selector You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.

How do you check if a dropdown is selected in Javascript?

Use the tagName property to check if an element is a select dropdown, e.g. if (select. tagName === 'SELECT') {} . The tagName property returns the tag name of the element on which it was accessed. Note that the property returns tag names of DOM elements in uppercase.


1 Answers

mySelect.value is a W3C standard at least since October 1st, 1998. See the DOM Level 1 Specification. However, some IE browsers released after that date do not support it, including IE8 (I just tested it).

Edit: As @kennebec pointed out, the issue with IE8 is that it wont use the option's text when there is no value set. If all your options do have a value set, then myselect.value will work on IE8.

like image 140
Étienne Miret Avatar answered Sep 28 '22 08:09

Étienne Miret