简体   繁体   中英

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?

Without making too many assumptions (ie 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).

就像这样简单:

options[selectedIndex].id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM