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

Time:04-13

I'm trying to modify and example from this same page but its not working as I want.

I have two groups in a select, and I want chose any option from one of the second group "Unique" and if you select any option from that group show Div, else show nothing.

the html:

<div >
<table>
  <tr>
   <td><input  type="email" 
name="mail[]" required /> 
</td>
  <td>
    <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  label="Unique">
        <option value="Diplomacy">Diplomacy</option>
        <option value="Survival">Survival</option>
      </optgroup>
    </select>
  </td>
<td>
  </tr>
</table>  
</div>  

<div  id="mydiv">
<h4 >Check</h4>
Increased through making items, sewing and cooking.<br>
<input  type="checkbox" name="checkpoint" 
checked required/>  
</div>

the Js:

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

css :

.extras{
display: none;
}

CodePudding user response:

You can access the optgroup by finding the selected option, using closest() to find the enclosing optgroup tag, then accessing it's label attribute

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 >
  <table>
    <tr>
      <td><input  type="email" name="mail[]" required />
      </td>
      <td>
        <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  label="Unique">
            <option value="Diplomacy">Diplomacy</option>
            <option value="Survival">Survival</option>
          </optgroup>
        </select>
      </td>
      <td>
    </tr>
  </table>
</div>

<div  id="mydiv">
  <h4 >Check</h4>
  Increased through making items, sewing and cooking.<br>
  <input  type="checkbox" name="checkpoint" checked required/>
</div>

  • Related