Michael Schwartz Michael Schwartz - 7 months ago 26
Javascript Question

Checkbox Menu Toggle

If checkbox1 is checked none of the others should be.
If checkbox2 is checked none of the others should be.

Sounds simple right? Well my problem here is I want to be able to also toggle a single menu and I'm having trouble figuring it out.

If anyone can help it'd be greatly appreciated.



$("label").on("click", function() {
$(this).toggleClass("active")
})

.d1, .d2, .d3 {
display: none;
}

#d1:checked ~ .d1 {
display: block;
}
#d2:checked ~ .d2 {
display: block;
}
#d3:checked ~ .d3 {
display: block;
}

.active {
color: #6d4dfe;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="menubar" id="d1">
<label for="d1">Open 1</label>
<input type="checkbox" name="menubar" id="d2">
<label for="d2">Open 2</label>
<input type="checkbox" name="menubar" id="d3">
<label for="d3">Open 3</label>

<div class="d1"><div class="hi">Lorem ipsum dolor.</div></div>
<div class="d2">Lorem ipsum dolor sit amet.</div>
<div class="d3">Lorem ipsum dolor sit amet, consectetur adipisicing.</div>




Answer

Assuming you have some reason to prefer checkboxes to radios, I believe this will do what you want:

$("input:checkbox").on("change", function() {
  $(this).toggleClass("active");
  $("input:checkbox").not(this).removeClass("active").prop('checked', false);
})
.d1, .d2, .d3 {
  display: none;
}

#d1:checked ~ .d1 {
  display: block;
}
#d2:checked ~ .d2 {
  display: block;
}
#d3:checked ~ .d3 {
  display: block;
}

.active {
  color: #6d4dfe;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="menubar" id="d1">
<label for="d1">Open 1</label>
<input type="checkbox" name="menubar" id="d2">
<label for="d2">Open 2</label>
<input type="checkbox" name="menubar" id="d3">
<label for="d3">Open 3</label>

<div class="d1"><div class="hi">Lorem ipsum dolor.</div></div>
<div class="d2">Lorem ipsum dolor sit amet.</div>
<div class="d3">Lorem ipsum dolor sit amet, consectetur adipisicing.</div>

Comments