Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get selected option ID?

to get the selected value from HTML select:

options[selectedIndex].value

what if i want to get the "id" on the selected option?

like image 271
h3n Avatar asked Dec 15 '09 02:12

h3n


People also ask

How do I get the selected option ID?

Getting the selected ID using the selectedIndex and options properties # The options property returns an HTMLOptionsCollection , an array-like collection of options for a select element. You can pair it with the selectedIndex property to get the selected option . Then, you can use the id property to get its ID.

How do you get the selected option ID in react?

You can add an onChange event handler to the select which checks for the selected index and retrieve the id from the selected option. This is a bit of an anti-pattern for React.

How do you get the selected option value in a form?

var getValue = document. getElementById('ddlViewBy'). selectedOptions[0]. value; alert (getValue); // This will output the value selected.

How do I get the selected option in dropdown?

Answer: Use the jQuery :selected Selector You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.


1 Answers

Without making too many assumptions (i.e. select is a valid SELECT Element),

var options = select.options;
var id      = options[options.selectedIndex].id;
var value   = options[options.selectedIndex].value;

or,

var options = select.options;
var value   = (options.selectedIndex != -1) ? options[selectedIndex].value : null;
var id      = (options.selectedIndex != -1) ? options[selectedIndex].id : null;

Always check for falsity (or values that evaluate to false). Ex 2 sets variables to null (if there is nothing selected).

like image 174
Michiel Kalkman Avatar answered Oct 16 '22 09:10

Michiel Kalkman