bboooooyintheuk
bboooooyintheuk

Reputation: 143

Showing/hiding checkbox based on another checkbox selection

Looking to have it so that when the first checkbox is selected (geographic_checkbox), a further 2 checkboxes are displayed (regions,cities &towns_checkbox and ringfencing_checkbox), but for some reason my code is not working.

$('#geographic_checkbox').on('click', function() {
  if (this.checked) {
    $('#geographic_suboptions').removeClass('hidden');
  } else {
    $('#geographic_suboptions').addClass('hidden');
  }
});
.hidden {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="targeting">
  <h1>Targeting</h1>
  <ul>
    <li>
      <input type="checkbox" name="geographic" value="0.00" id="geographic_checkbox" onclick="GeographicFunction()">Geographic<br>
      <p id="geographic_text" style="display:none">+£0.08 CPC</p>
      <div id="geographic_suboptions" class="hidden">
        <ul>
          <li><input type="checkbox" name="regions,cities&towns" value="0.08" id="regions,cities&towns_checkbox" onclick="RegionsFunction()">Regions, Cities & Towns<br></li>
          <p id="regions,cities&towns_text" style="display:none">+£0.08 CPC</p>
          <li><input type="checkbox" name="ringfencing" value="0.09" id="ringfencing_checkbox" onclick="RingfencingFunction()">Ring-Fencing<br></li>
          <p id="ringfencing_text" style="display:none">+£0.08 CPC</p>
        </ul>
      </div>
    </li>
  </ul>
</div>

Upvotes: 0

Views: 48

Answers (1)

johannchopin
johannchopin

Reputation: 14844

Actually for such a feature you not really need javascript since css provide the :checked selector:

.hidden {
  display: none;
}

ul input:checked ~ #geographic_suboptions {
  display: inline;
}
<div class="targeting">
  <h1>Targeting</h1>
  <ul>
    <li>
      <input type="checkbox" name="geographic" value="0.00" id="geographic_checkbox">Geographic<br>
      <p id="geographic_text" style="display:none">+£0.08 CPC</p>
      <div id="geographic_suboptions" class="hidden">
        <ul>
          <li><input type="checkbox" name="regions,cities&towns" value="0.08" id="regions,cities&towns_checkbox">Regions, Cities & Towns<br></li>
          <p id="regions,cities&towns_text" style="display:none">+£0.08 CPC</p>
          <li><input type="checkbox" name="ringfencing" value="0.09" id="ringfencing_checkbox">Ring-Fencing<br></li>
          <p id="ringfencing_text" style="display:none">+£0.08 CPC</p>
        </ul>
      </div>
    </li>
  </ul>
</div>

Upvotes: 1

Related Questions