I’m trying to create a few checkboxes that when checked, will check another… which I got to work! But, the problem I’m having now is that if multiple are selected and one is unchecked at any point, the additional checkbox get unchecked no matter what. I’d like to find a way to have the additional checkbox stay checked, as long as one of the others is, and uncheck if none are selected.
For example: I have 4 checkboxes, if a user selects #1 I want to check #2. Or if a user selects #1 + #3, check #2, but if #3 is unchecked, #2 stays as long as 1,3, or 4 are. I hope this makes sense. I’ve been trying different things, but this is the code where I landed. Any help, advice on a better way to accomplish this would be greatly appreciated.
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
var chk3 = $("input[type='checkbox'][value='3']");
var chk4 = $("input[type='checkbox'][value='4']");
chk1.on('change', function(){
chk2.prop('checked',this.checked);
});
chk3.on('change', function(){
chk2.prop('checked',this.checked);
});
chk4.on('change', function(){
chk2.prop('checked',this.checked);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="1" class="user_name">1
<br>
<input type="checkbox" value="2" class="user_name">2
<br>
<input type="checkbox" value="3" class="user_name">3
<br>
<input type="checkbox" value="4" class="user_name">4
2
Answers
If you want to keep
chk2
checked until all others are unchecked, you have to look for the status of all other boxes in each event handler. Ideally, you would create a function for that, so you don’t need to repeat your code for all handlers.You can also add this function to the change handler of
chk2
if you want to prevent manual change of that checkbox.For the record: alternative without JQuery, using event delegation and a css selector to query the state of the other checkboxes: