Stephen Brown
Stephen Brown

Reputation: 574

Accessing data in a DataTable from a button click within a row

I can access the data row by the following simple method:

$('#received-body tr').click( function(){
    aData = received_table.fnGetData(this);
    selected_received_id = aData[0];
    alert( selected_received_id );
});

but I can't access them from the button called .received-update in one of the rows:

$('#received-body .received-update').click( function(){
    alert( 'update' ); // works
    aData = received_table.fnGetData( $(this).parents('tr')); // fails
    selected_received_id = aData[0];
    alert( 'update:' + selected_received_id );                      
});

Any help appreciated

Upvotes: 2

Views: 10022

Answers (4)

Thulasiram Bandaru
Thulasiram Bandaru

Reputation: 101

Below piece of code will help,

var table = $('#tableID').DataTable();
var row_data;
$('#tableID tbody').on( 'click', 'button', function () {
    row_data = table.row( $(this).parents('tr') ).data();
    console.log(row_data); // you will get the row data
});

Upvotes: 1

Kevin Traas
Kevin Traas

Reputation: 415

You can solve your problem by replacing

    aData = received_table.fnGetData($(this).parents('tr'));

with

    aData = received_table.fnGetData($(this).parents('tr')[0]);


This same syntax is also required for calls to received_table.fnGetPosition()

Upvotes: 4

Techie
Techie

Reputation: 45124

aData = recieved_table.fnGetData($(this).parent('tr')); 

Try .parent() instead of .parents() because .parents() get the parent of each element in the current set of matched elements. .parent() will only work if the tr is a direct children of the tr. In that scenario .closest() will be ideal as shown below.

aData = recieved_table.fnGetData($(this).closest('tr'));

If above didn't work out for you, try filter method to reduce the set of matched elements.

Upvotes: 0

Adil
Adil

Reputation: 148110

You may need to use closest as parents() might be giving more then one rows. While closest get the first match up the DOM hierarchy.

aData = recieved_table.fnGetData($(this).closest('tr')); // fails

Upvotes: 0

Related Questions