This is my select box code now
<select id="header1_cbocity">
<option value="2">Ahmedabad</option>
<option value="4">Bangalore</option>
<option value="14">Chennai</option>
<option value="20">Delhi</option>
<option value="33">Gurgaon</option>
<option value="167">Switzerland</option>
<option value="261">Tanzania</option>
<option value="168">Thailand</option>
<option value="263">Uganda</option>
<option value="169">United Kingdom (U.K)</option>
<option value="170">United States (U.S)</option>
</select>
and i want to add optgroup label only for country like below
<select id="header1_cbocity">
<option value="2">Ahmedabad</option>
<option value="4">Bangalore</option>
<option value="14">Chennai</option>
<option value="20">Delhi</option>
<option value="33">Gurgaon</option>
<optgroup label="Country">
<option value="167">Switzerland</option>
<option value="261">Tanzania</option>
<option value="168">Thailand</option>
<option value="263">Uganda</option>
<option value="169">United Kingdom (U.K)</option>
<option value="170">United States (U.S)</option>
</optgroup>
</select>
i am trying with jquery code but couldn’t add optgroup label for Country, so i need help
I’d suggest:
JS Fiddle demo.
I’d also suggest adding a definitive means to identify which
optionelements represent a country, in the demo below I’ve used aclass, but a customdata-*attribute could just as easily be used. Given the markup:(Note that I’ve added
Bahamas(in order to show how to handle dealing with non-consecutive states/countries).With the following jQuery:
JS Fiddle demo.
Further, assuming that you’ve placed a definition of some kind (in the following I use a custom,
data-defn, attribute) you can createoptgroupelements to encompass those:With the jQuery:
JS Fiddle demo.
Of course, with a selector that specifies only those elements with a
data-defnattribute, you don’t necessarily need to supply everyoptionwith such an attribute:JS Fiddle demo.
References:
appendTo().closest().wrapAll().