Background
There's a large list of options - dozens - in a drop-down list using an XHTML Select element.
Using JavaScript, I need to retrieve the selected option.
Problem
Currently I'm using jQuery :selected
CSS selector and it works as expected, but this approach isn't efficient as it takes a while to find selected option - obviously, it depends on CPU power of client machine, but in a decent Intel Core 2 wit开发者_高级运维h 4GB of RAM, there's an excesive performance penalty.
Issue
Either using jQuery or plain JavaScript and DOM, I need to get selected option of this XHTML Select element in an efficient way.
Thank you in advance.
Should be as easy as:
// assuming `select` refers to the select DOM element
var selectedElement = select.options[select.selectedIndex];
See HTMLSelectElement [MDN].
Update:
In newer browsers which support the following methods (they are part of HTML5), you could also use:
var selectedElement = select.item(select.selectedIndex);
// or
var selectedElement = select[select.selectedIndex];
// or
var selectedElement = select.selectedOptions[0];
var dropDown = document.getElementById("yourId");
dropDown.options[dropDown.selectedIndex];
Use the "vanilla" DOM selectedIndex
property of the <select>
.
var $select = $('#mySelect'),
si = $select.get(0).selectedIndex,
$selectedOpt = $select.children('option:eq(' + si + ')');
<select id="sel">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
$("#sel").val()
精彩评论