Rajasekhar
Rajasekhar

Reputation: 2455

how to get columns of selected rows using jquery

I tried with below code and getting alert of the column name but didn't get all columns of the multiple selected rows. Here is the sample code.

$('body').on('click', 'td', function() {
    var selectedRows= $(this).toggleClass('selected');        
    var holdNames = $(this).closest("tr").find("td:eq(2)").text();
    $("#holdNames").val(holdNames);

    var holdsArr = [];
    for ( var index=0; index<selectedRows.length;index++) {
        holdsArr.push(holdNames[index]);
    };
    alert(holdsArr);
 });

Upvotes: 0

Views: 178

Answers (1)

Rylee
Rylee

Reputation: 1656

The below code will alert the 3rd <td> in each selected row e.g. Text1,Text2,Text3

$('body').on('click', 'tr', function() {
    $(this).toggleClass('selected');
    var holdNames = $(this).children().eq(2).text();
    $("#holdNames").val(holdNames);

    var selectedRows= $('tr.selected');
    var holdsArr = [];
    for ( var index=0; index<selectedRows.length;index++) {
        var name = selectedRows.eq(index).children().eq(2).text();
        holdsArr.push(name);
    };
    alert(holdsArr);
});

A better approach would be

  var holdsArr = [];
$(document).on('click','tr',function(){
    var $tr = $(this);
    $tr.toggleClass('selected');
    updateHoldsArr();
    alert(holdsArr);
});

function updateHoldsArr(){
    var $trs = $('tr.selected'),
        arr = [];
    $trs.each(function(){
        arr.push($(this).children().eq(2));
    });
    holdsArr = arr;
}

Upvotes: 1

Related Questions