Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check/uncheck a checkbox in the table row when any checkbox in the same row is clicked

I have a simple table as following which has checkboxes in the first and last columns of each row.

<table style="width:100%">
  <tr>
    <td><input type="checkbox" /></td>
    <td>Smith</td> 
    <td><input type="checkbox" /></td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>Jackson</td> 
    <td><input type="checkbox" /></td>
  </tr>
</table>

Problem: When I check/uncheck the last column's checkbox in the first row, the first column's checkbox in the same row should be checked/unchecked. Similarly, if I check/uncheck the first column's checkbox, the corresponding last column checkbox should be checked/unchecked.

How can I achieve this in javascript? Any help or pointers would be really appreciated.

Here is the fiddle which I have created: Fiddle

Thank you.

like image 665
ShellZero Avatar asked Mar 28 '16 16:03

ShellZero


1 Answers

Use :checkbox selector to select input type checkbox elements.

Try this:

$(':checkbox').on('change', function() {
  $(this).closest('tr').find(':checkbox').prop('checked', this.checked);
});
table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table style="width:100%">
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Smith</td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Jackson</td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
</table>

Using JavaScript:

Use querySelectorAll('[type="checkbox"]') to find checkbox elements.

Try this:

var checkboxes = document.querySelectorAll('[type="checkbox"]');
[].forEach.call(checkboxes, function(checkbox) {
  checkbox.onchange = function() {
    var currentRow = this.parentNode.parentNode;
    var cbElems = currentRow.querySelectorAll('[type="checkbox"]');
    [].forEach.call(cbElems, function(cb) {
      cb.checked = this.checked;
    }.bind(this))
  };
});
table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}
<table style="width:100%">
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Smith</td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Jackson</td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
</table>
like image 155
Rayon Avatar answered Sep 30 '22 07:09

Rayon