<html>
<body>
<select name="lstparameters">
<optgroup value="100" label="Swedish Cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</optgroup>
<optgroup value="101" label="German Cars">
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</optgroup>
</select>
</body>
</html>
How to get optgroup values from javascript?I want to get 100 and 101 values.
The <optgroup> tag is used to group related options in a <select> element (drop-down list). If you have a long list of options, groups of related options are easier to handle for a user.
A style attribute on an <optgroup> tag assigns a unique style to the option group. Its value is CSS that defines the appearance of the option group.
You can get the optgroup elements and read the value
attribute
var values = Array.from(document.querySelectorAll('select[name="lstparameters"] > optgroup')).map(el => el.getAttribute('value'));
alert(values);
//if you want old browser support
var values = [].slice.call(document.querySelectorAll('select[name="lstparameters"] > optgroup')).map(function(el) {
return el.getAttribute('value')
});
alert(values);
<select name="lstparameters">
<optgroup value="100" label="Swedish Cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</optgroup>
<optgroup value="101" label="German Cars">
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</optgroup>
</select>
For those like me wanting to get the optgroup
label
of the selected
option
, do this:
document.querySelector('select[name="lstparameters"] option:checked').parentElement.label
Having a select
with an id
simplifies the selector:
document.querySelector('#lstparameters option:checked').parentElement.label
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With