I have 2 columns 'Select' & 'Super' these columns have checkboxes, and can be selected or unselected by the user. What I am looking for is a jQuery solution to :
- If any checkbox in Column B (super) is selected then the corresponding checkbox in Column A (select) should be checked
- If any checkbox in Column A (select) is unselected, then the corresponding checkbox in Column B (super) should be unchecked
The HTML code that I have is:
<td>
<input type="checkbox" id="select1" checked="checked" >
</td>
<td><input type="checkbox" id="super1" >
</td>
</tr>
<tr>
<td><input type="checkbox" id="select2" >
</td>
<td><input type="checkbox" id="super2" >
</td>
</tr>
<tr>
<td><input type="checkbox" id="select3" checked="checked" >
</td>
<td><input type="checkbox" id="super3" checked="checked" >
</td>
</tr>
<tr>
<td><input type="checkbox" id="select4" checked="checked" >
</td>
<td><input type="checkbox" id="super4" checked="checked" >
</td>
</tr>```
CodePudding user response:
First you need to add a common class to all select checkboxes, and a common class to all super checkboxes
$(function(){
$('.super-checkbox').change(function(e){
const chk = $(this);
if(chk.is(':checked')){
//Super is checked
// get the closest tr
const tr = chk.closest('tr');
//find the select checkbox, under this tr
const selectChk = tr.find('.select-checkbox');
//Check this select checkbox
selectChk.prop('checked',true);
}
});
$('.select-checkbox').change(function(e){
const chk = $(this);
if(!chk.is(':checked')){
//Select is not checked
// get the closest tr
const tr = chk.closest('tr');
//find the super checkbox, under this tr
const selectChk = tr.find('.super-checkbox');
//un-Check this select checkbox
selectChk.prop('checked', false);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="checkbox" id="select1" checked="checked" >
</td>
<td><input type="checkbox" id="super1" >
</td>
</tr>
<tr>
<td><input type="checkbox" id="select2" >
</td>
<td><input type="checkbox" id="super2" >
</td>
</tr>
<tr>
<td><input type="checkbox" id="select3" checked="checked" >
</td>
<td><input type="checkbox" id="super3" checked="checked" >
</td>
</tr>
<tr>
<td><input type="checkbox" id="select4" checked="checked" >
</td>
<td><input type="checkbox" id="super4" checked="checked" >
</td>
</tr>
</table>