I have 3 Divs, every div contains 2 inputs, I want to only check checkboxes in the same div with id and unchecked from other divs.
HTML is :
<div class="dashboard">
<div id="fr">
<h3>Fruits</h3>
<label>
<input type="checkbox" name="check1" />Kiwi</label>
<label>
<input type="checkbox" name="check2" />Jackfruit</label>
</div>
<div id="an">
<h3>Animals</h3>
<label>
<input type="checkbox" name="check1" />Tiger</label>
<label>
<input type="checkbox" name="check2" />Sloth</label>
</div>
<div id="veg">
<h3>vegetables</h3>
<label>
<input type="checkbox" name="check1" />Tiger</label>
<label>
<input type="checkbox" name="check2" />Sloth</label>
</div>
</div>
and JQuery is :
$("input:checkbox").on('click', function() {
var $box = $(this);
if ($box.is(":checked")) {
var group = "input:checkbox[name='" + $box.attr("name") + "']";
$(group).prop("checked", false);
$box.prop("checked", true);
} else {
$box.prop("checked", false);
}
});
see live example
If you only want to allow checkboxes to be checked within a single div, you can use jQuery to traverse the DOM using closest(), siblings() and find() to retrieve the external checkboxes before de-selecting them.
Try this:
$("input:checkbox").on('change', e => {
$(e.target).closest('div').siblings().find('input:checkbox').prop('checked', false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dashboard">
<div id="fr">
<h3>Fruits</h3>
<label><input type="checkbox" name="check1" />Kiwi</label>
<label><input type="checkbox" name="check2" />Jackfruit</label>
</div>
<div id="an">
<h3>Animals</h3>
<label><input type="checkbox" name="check1" />Tiger</label>
<label><input type="checkbox" name="check2" />Sloth</label>
</div>
<div id="veg">
<h3>vegetables</h3>
<label><input type="checkbox" name="check1" />Tiger</label>
<label><input type="checkbox" name="check2" />Sloth</label>
</div>
</div>