Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently get selected option in a drop-down list (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 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.

like image 985
Matías Fidemraizer Avatar asked Aug 05 '11 13:08

Matías Fidemraizer


People also ask

How do you display a selected value in a drop down list?

Method 1: Using the value property: The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.

How do I select a dropdown value in HTML?

The select tag in HTML is used to create a dropdown list of options that can be selected. The option tag contains the value that would be used when selected. The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute.

How do you change the selection options in HTML?

We can change the HTML select element's selected option with JavaScript by setting the value property of the select element object. We have a select drop down with some options and 2 buttons that sets the selected options when clicked.

How do you get the selected value of dropdown in PHP without submit?

How do you get the selected value of a dropdown in PHP without submitting? You have to use JavaScript for this, PHP is server side language so it will not able to get drop down value without form submitting. by using JavaScript you can get it .


2 Answers

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];
like image 104
Felix Kling Avatar answered Oct 06 '22 19:10

Felix Kling


var dropDown = document.getElementById("yourId");
dropDown.options[dropDown.selectedIndex];
like image 43
Kevin Bowersox Avatar answered Oct 06 '22 20:10

Kevin Bowersox