Search code examples
javascripthtmloptgroup

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.


Solution

  • 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