aba2s
aba2s

Reputation: 522

Get selected optgroup in JavaScript

I have the below select tag with two optgroup.

<select id="linkSelector" class="form-control" onchange="linkDropDown();">
  <optgroup label="Input">
   <option value="default">Road type</option>
   <option value="lanes">Lanes</option>
   <option value="length">Length</option>
   <option value="speed">Speed</option>
  </optgroup>

  <optgroup label="Ouput">
   <option value="congestion">Congestion</option>
   <option value="speed_output">Speed</option>
   <option value="travel_time">Travel Time</option>
  </optgroup>
</select>

I would like to execute myFuncton() depending on the selected optgroup. For example if one of the dropdown value belong to <optgroup label="Input">, then execute myFunction().

I tried this:

var linkSelector = document.getElementById('linkSelector')
opt = linkSelector.getElementsByTagName('optgroup')
if (opt[0].label =='Input'){
    myFunction()
}

Upvotes: 0

Views: 595

Answers (1)

Taylor Earl
Taylor Earl

Reputation: 66

One way to go about this, would be to get the selected option for the select field, then find out it's parent's label.

var label = document.getElementById('linkSelector').selectedOptions[0].parentElement.label;
if (label === "Input") {
  myFunction();
}

Upvotes: 3

Related Questions