to get the selected value from HTML select:
options[selectedIndex].value
what if i want to get the "id"
on the selected option?
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.
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.
var getValue = document. getElementById('ddlViewBy'). selectedOptions[0]. value; alert (getValue); // This will output the value selected.
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.
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).
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