The goal of the code is to display only relevant divs when a checkbox is checked. I added on div for Mark as a full check box. So if I check the mark as full, it will show and if I uncheck it, it won’t show. However, if I check other checkboxes, it will remain on the screen. So I was wondering if there’s a way to hide it once other checkboxes are working. In my actual code, I have some divs showing for all the checkboxes so I want to show divs only when it’s checked and hide the div once its corresponding checkbox is unchecked.
let boxes = document.querySelectorAll("input[type=checkbox]");
boxes.forEach(b => b.addEventListener("change", tick));
function tick(e) {
let state = e.target.checked; // save state of changed checkbox
console.log(state);
boxes.forEach(b => b.checked = false); // clear all checkboxes
e.target.checked = state; // restore state of changed checkbox
}
$("#markAsFullChange").hide();
$("[name='markAsFull']").click(function() {
if($(this).is(":checked")) {
$("#markAsFullChange").show();
} else {
$("#markAsFullChange").hide();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="testForm" action="" method="POST">
<p>Select one of the checkboxes:</p>
<label><input name="changeLocation" type="checkbox">Change Location</label>
<label><input name="updateLocation" type="checkbox">Update Location</label>
<label><input name="retireLocation" type="checkbox">Retire</label>
<label><input name="markAsFull" type="checkbox">Mark as full</label>
<label><input name="moveContents" type="checkbox">Move Contents</label>
<div id="markAsFullChange">
<div>
<label>Select a location to mark as full:</label>
</div>
<div>
<label>I have a dropdown list here in actual code</label>
</div>
</div>
</form>
3
Answers
You can first hide all the associated div elements before showing the appropriate one.
The issue was because the function to show/hide the
markAsFullChange
div only is binded to one click handler, the one formarkAsFull
checkbox. Other checkboxes do not fire the function.Side note #1, unless you are doing some complex DOM traversing or using jQuery’s effects… Go for plain JS.
Else, it is like using a SUV to go from the front yard to the back yard.
Side note #2, you are using checkboxes like the radio behaves natively… Using radios would spare you a function.
Less code is less debugging.
Here is a no jQuery solution.
you can only use css for that and only radio instead