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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With