ageoff
ageoff

Reputation: 2828

Get rows with checked boxes in a table

So I am trying to find the rows with a checked box and then grab a column value form that row. Here is what I have so far:

$('#myTable tbody tr').each(function () {
    var chckbox = $(this).find('.checkItem');
    if (chckbox.checked) {  
    ids.push($(this).find(".id").html());
    }
});

The problem right now is it never gets inside the if statement. The class names are all correct.

Upvotes: 0

Views: 90

Answers (4)

Alnitak
Alnitak

Reputation: 339816

This will return the array of IDs all in one go:

var ids = $('#myTable .checkItem:checked').map(function() {
    return $(this).closest('tr').find('.id').html();
}).get();

Note the use of .map rather than a push inside a .each loop.

.map is usually the function you want to use if you have an array of elements and want to retrieve some value from each of them into an array.

Upvotes: 1

omma2289
omma2289

Reputation: 54619

It would also work if you do it this way:

$('#myTable tbody tr .checkItem:checked').each(function () {
    ids.push($(this).closest('tr').find(".id").html());
});

Upvotes: 1

Simon Adcock
Simon Adcock

Reputation: 3562

$('#myTable tbody tr').each(function () {
    var chckbox = $(this).find('.checkItem');
    if (chckbox.prop('checked')) {  
        ids.push($(this).find(".id").html());
    }
});

jQuery .prop

Upvotes: 3

luk2302
luk2302

Reputation: 57114

$('#myTable tbody tr').each(function () {
  var chckbox = $(this).find('.checkItem:checked');
  if (chckbox.length) {  
    ids.push($(this).find(".id").html());
  }
});

Upvotes: 0

Related Questions