开发者

Efficiently get selected option in a drop-down list (XHTML Select element)

开发者 https://www.devze.com 2023-03-25 08:48 出处:网络
Background There\'s a large list of options - dozens - in a drop-down list using an XHTML Select element.

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()
0

精彩评论

暂无评论...
验证码 换一张
取 消