简体   繁体   中英

set html option value with optgroup in select field using JavaScript

I tried to set the option value in the select field using

document.getElementById("select").value="android";

But i want it to store as "android" in the optgroup "phones"

Is there anyway to set value of option with the optgroup value .

The value of an select element should be unique, else while getting the value how would you find out which optgroup is selected

That said, you can use a css selector to find the select element and then set its selected property

var opt = document.querySelector('#select optgroup[label="Phones"] [value="android"]');
if (opt) {
    opt.selected = true;
}

Demo: Fiddle

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