Fares Omrani Fares Omrani - 4 months ago 29
HTML Question

Jquery check the checkbox in td before

I have a table in html with td contains a checkbox input like this

<table id="my_table">
<tr>
<td><input type="checkbox" name="td1"></td>
<td><input type="checkbox" name="td2"></td>
</tr>
<tr>
<td><input type="checkbox" name="td3"></td>
<td><input type="checkbox" name="td4"></td>
</tr>
</table>
<script>
$('[type=checkbox]').change(function () {
if($(this).is(":checked")) {
$(this).closest('td').prev().find('input[type=checkbox]').prop('checked', true);
}
});
</script>


I wanna create a function in jquery that when I check a checkbox the one above it is checked (example if td3 is checked then td1 is checked also) but the one i used check the input next to this and not above it.

Thanks for your help

Answer

Use index() to get index of clicked checkbox td and accordingly check another previous checkbox

$('[type=checkbox]').change(function () {
    index = $(this).closest('td').index();
    if($(this).is(":checked")) {
       $(this).closest('tr').prev().find('input:checkbox').eq(index).prop('checked', true);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="my_table">
  <tr>
   <td><input type="checkbox" name="td1"></td>
   <td><input type="checkbox" name="td2"></td>
  </tr>
<tr>
   <td><input type="checkbox" name="td3"></td>
   <td><input type="checkbox" name="td4"></td>
  </tr>
 </table>