Skip to content Skip to sidebar Skip to footer

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?

Solution 1:

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

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

or,

var options = select.options;
varvalue   = (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).

Solution 2:

It's as simple as:

options[selectedIndex].id

Post a Comment for "How To Get Selected Option Id?"