Question

[Solved] Get selected rows first column value in datatable

$('.example tbody').on('click', 'tr', function (){
    var id = this.id;
    var index = $.inArray(id, selected);
    if (index === -1) 
    {
    selected.push(id);
    } else 
    {
    selected.splice(index, 1);
    }
    $(this).toggleClass('selected');
});
$('#btn').click(function (){
    var dataArr = [];
    var rowCount = table.rows('.selected').data().length;
    alert(rowCount);
});

Here is the code for select multiple rows. On clicking the button I need to get the selected rows first column value and store in array dataArr[]. Please help me to fix this.

Solution #1:

Try this:

DEMO

$('#btn').click(function (){
    var dataArr = [];
    $.each($("#example tr.selected"),function(){ //get each tr which has selected class
        dataArr.push($(this).find('td').eq(0).text()); //find its first td and push the value
        //dataArr.push($(this).find('td:first').text()); You can use this too
    });
    console.log(dataArr);
});

UPDATE

You can get using some native functions of dataTables too as below:

$('#btn').click(function (){
    var dataArr = [];
    var rows = $('tr.selected');
    var rowData = table.rows(rows).data();
    $.each($(rowData),function(key,value){
        dataArr.push(value["name"]); //"name" being the value of your first column.
    });
    console.log(dataArr);
});

UPDATED DEMO

Solution #2:

Guruprasad code (perfect) with small handy updates.

var table= $('#YourTableName').DataTable();
$('#button').click(function () {
           var arr = [];
           $.each(table.rows('.selected').data(), function() {
               arr.push(this["ColomnName"]);
           });
});
Respondent: Dinand
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy