Surabhi Surabhi - 2 months ago 22
jQuery Question

Select all checkbox in the same column

I am trying to implement something similar to Checking checkbox in column

I have two select all checkboxes in a table and selecting one would select all the checkboxes of the same column.

It an ASP.NET GridView. Plunker

function CheckHeaderCheckboxAll(obj, gridname) {

var objId = obj.id;


var table= $(obj).closest('table');
$('td input:checkbox',table).prop('checked',this.checked);


}


Can someone please help me with this?

Answer

Basic idea is to select the cell, get the index, and than select the other table cells of the table with that index.

$("th input[type='checkbox']").on("change", function() {
   var cb = $(this),          //checkbox that was changed
       th = cb.parent(),      //get parent th
       col = th.index() + 1;  //get column index. note nth-child starts at 1, not zero
   $("tbody td:nth-child(" + col + ") input").prop("checked", this.checked);  //select the inputs and [un]check it
});
th { background-color: #CCC; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>
        <input type="checkbox">
      </th>
      <th>
        <input type="checkbox">
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <input type="checkbox">
      </td>
      <td>
        <input type="checkbox">
      </td>
    </tr>
    <tr>
      <td>
        <input type="checkbox">
      </td>
      <td>
        <input type="checkbox">
      </td>
    </tr>
    <tr>
      <td>
        <input type="checkbox">
      </td>
      <td>
        <input type="checkbox">
      </td>
    </tr>
  </tbody>
</table>

If you want to do it with inline event handler like you have it, your code would look like

function CheckHeaderCheckboxAll(obj) {
   var cb = $(obj),           //checkbox that was changed
       th = cb.parent(),      //get parent th
       col = th.index() + 1;  //get column index. note nth-child starts at 1, not zero
   $("tbody td:nth-child(" + col + ") input").prop("checked", obj.checked);  //select the inputs and [un]check it
}
Comments