1

I'm trying to get values of a table with jQuery. Every table row has a checkbox at the begining. How can I copy data of each row, but only if it's checked. All checkboxes and rows has the same class. Now I'm using this code:

var table = $("table");
    var allRows = [];
    table.find('tr').each(function (i, el) {
        if($('input:checkbox:checked').length > 0){
            var $tds = $(this).find('td'),
            name = $tds.eq(2).text(),
            surname = $tds.eq(4).text();
            allRows.push(surname+";"+name+";"+"\n");
        }
    });
    allRows = allRows.join("");

But it's getting all the lines. How can I do this only for lines which are checked?

passwd
  • 2,883
  • 3
  • 12
  • 22

2 Answers2

5

$('.theClass:checkbox:checked') will give you all the checked checkboxes with the class theClass. See also Get all checked checkboxes

Satpal
  • 132,252
  • 13
  • 159
  • 168
Daniel Taub
  • 5,133
  • 7
  • 42
  • 72
2

As of now you are checking any checkbox is checked. the condition needs to be changed.

You need to check the :checked state of the chechbox in current row while iterating.

if($(this).find(':checkbox:checked').length > 0){
   //your existing code
} 
Satpal
  • 132,252
  • 13
  • 159
  • 168