Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get optgroup value from Javascript?

Tags:

javascript

<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.

like image 351
Prinu Philip Avatar asked Apr 14 '16 06:04

Prinu Philip


People also ask

How do I use Optgroup tags?

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.

Can you style Optgroup?

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.


2 Answers

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>
like image 94
Arun P Johny Avatar answered Nov 18 '22 08:11

Arun P Johny


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
like image 6
MarredCheese Avatar answered Nov 18 '22 07:11

MarredCheese