This is a simple question but I cannot find any reference so here it goes.
Assume I have a select element:
<select id="sel">
<option value="1">1</option>
<option value="2">2</option>
</select>
Now I want to get its selected option's value
. Most often I see this kind of snippet being used:
var sel = document.getElementById('sel');
console.log( sel.options[sel.selectedIndex].value ); //1
Which works great. However, I've found out that select
elements also have a value property:
console.log( sel.value ); //1
See fiddle with both examples.
The second form is not only much simpler, it also works all the way back to IE6 (yes, I did actually test on that, here's the IE6 friendly version).
Is there a reason why the first approach is so much more widely accepted? Is there some incompatibility or corner-case issue with the second approach?
ps. My "most used approach" thesis was based mostly on personal experience, but as for reference, the two most upvoted answers in Get selected value in dropdown list using JavaScript? uses the first approach.