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.
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.
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.
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 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 .
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With