Anil Reddy Yarragonda
Anil Reddy Yarragonda

Reputation: 767

Row wise selecting the all checkboxes inside a table with using Jquery

I have a script that should check all the checkboxes inside a table row. But by using the below post i am able to check all the checkboxes inside table. I don't want this. I want to check the checkboxes in row wise only.

Reference post:

Jquery select all checkboxes in table

Sample HTML Code:

<table>
<tr>
    <th>
        <input type="checkbox" id="selectAll" />
    </th>
    <th>
        hi!
    </th>
</tr>
<tr>
    <td>
        <input type="checkbox" id="1"/>
    </td>
    <td>
        hi!
    </td>
</tr>
<tr>
    <td>
        <input type="checkbox" id="2"/>
    </td>
    <td>
        hi!
    </td>
</tr>
    </table>

Sample Jquery:

  $('#selectAll').click(function(e){
var table= $(e.target).closest('table');
$('td input:checkbox',table).prop('checked',this.checked);
});

See the below screenshots about my project

  1. Before clicking check All checkbox

enter image description here

  1. After checking Check All checkbox

enter image description here

Upvotes: 2

Views: 2073

Answers (1)

Milind Anantwar
Milind Anantwar

Reputation: 82231

Looks like you have duplicate ids for select all checkboxes. IDs must be unique. You can give same class to select all checkboxes(say selectAll) and then use class selector.

Also for targeting closest tr, You can traverse to closest tr rather than getting table element. and then find input checkboxes in them. like this:

$('.selectAll').click(function(e){
  var tr= $(e.target).closest('tr');
  $('td input:checkbox',tr).prop('checked',this.checked);
});

Upvotes: 1

Related Questions