如果来自 optgroup 的 select 选项之一被 selected Javascript 显示 Div/Hide

Show Div/Hide if one of the select options from optgroup is selected Javascript

我正在尝试从同一页面修改和示例,但它无法正常工作。

我在 select 中有两个组,我想从第二组“唯一”中选择任何选项,如果你 select 该组中的任何选项显示 Div, 否则什么都不显示。

html:

<div class="form-floating mb-3 mt-3">
<table>
  <tr>
   <td><input class="form-control input-lg email" type="email" 
name="mail[]" required /> 
</td>
  <td>
    <select class="form-select" name="skills[]" required>
      <optgroup Class="unique" label="Common">
        <option value="Extraction">Extraction</option>
        <option value="Hunting">Hunting</option>
        <option value="Farming">Farming</option>
      </optgroup>
      <optgroup class="unique" label="Unique">
        <option value="Diplomacy">Diplomacy</option>
        <option value="Survival">Survival</option>
      </optgroup>
    </select>
  </td>
<td>
  </tr>
</table>  
</div>  

<div class="mt-5 extras" id="mydiv">
<h4 class="text-dark">Check</h4>
Increased through making items, sewing and cooking.<br>
<input class="form-check-input" type="checkbox" name="checkpoint" 
checked required/>  
</div>

Js:

function showDiv(divId, element)
{
document.getElementById(divId).style.display = element.value == 
'Diplomacy'  || 'Survival' ? 'block' : 'none';
}

css :

.extras{
display: none;
}

您可以通过找到所选选项来访问 optgroup,使用 closest() 找到封闭的 optgroup 标签,然后访问它的标签属性

function doSomething(element) {
  // get optgroup
  let optgroup = element.options[element.options.selectedIndex].closest('optgroup').getAttribute('label')
  console.log(optgroup)
  if (optgroup == 'Unique') {
    console.log("do something ...")
  }
}
.extras {
  display: none;
}
<div class="form-floating mb-3 mt-3">
  <table>
    <tr>
      <td><input class="form-control input-lg email" type="email" name="mail[]" required />
      </td>
      <td>
        <select class="form-select" name="skills[]" onchange='doSomething(this)' required>
          <optgroup Class="unique" label="Common">
            <option value="Extraction">Extraction</option>
            <option value="Hunting">Hunting</option>
            <option value="Farming">Farming</option>
          </optgroup>
          <optgroup class="unique" label="Unique">
            <option value="Diplomacy">Diplomacy</option>
            <option value="Survival">Survival</option>
          </optgroup>
        </select>
      </td>
      <td>
    </tr>
  </table>
</div>

<div class="mt-5 extras" id="mydiv">
  <h4 class="text-dark">Check</h4>
  Increased through making items, sewing and cooking.<br>
  <input class="form-check-input" type="checkbox" name="checkpoint" checked required/>
</div>