h3n
h3n

Reputation: 5248

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?

Upvotes: 17

Views: 55965

Answers (2)

Michiel Kalkman
Michiel Kalkman

Reputation: 3054

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).

Upvotes: 16

zombat
zombat

Reputation: 94237

It's as simple as:

options[selectedIndex].id

Upvotes: 13

Related Questions