Reputation: 64943
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 with 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.
Upvotes: 7
Views: 17780
Reputation: 816770
Should be as easy as:
// assuming `select` refers to the select DOM element
var selectedElement = select.options[select.selectedIndex];
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];
Upvotes: 23
Reputation: 2356
<select id="sel">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
$("#sel").val()
Upvotes: 0
Reputation: 94489
var dropDown = document.getElementById("yourId");
dropDown.options[dropDown.selectedIndex];
Upvotes: 3
Reputation: 359956
Use the "vanilla" DOM selectedIndex
property of the <select>
.
var $select = $('#mySelect'),
si = $select.get(0).selectedIndex,
$selectedOpt = $select.children('option:eq(' + si + ')');
Upvotes: 2