Reputation: 195
I want to get values of a row in DataTables when a click on the button corresponding to this row, but when using this code i get undefined:
The buttons are being added like this:
function getdata()
{
$pdrs = Pdrs::select('ID_Piece', 'Designation', 'Status');
$result = DataTables::of($pdrs)
...
->addColumn('action', function($pdr){
return '<a href="#" class="btn btn-xs btn-primary Ajouter_au_panier" id="'.$pdr->ID_Piece.'"><i class="glyphicon glyphicon-shopping-cart"></i> Ajouter au panier</a>';})
->make(true);
return $result ;
}
the trigger is:
$(document).on('click', '.Ajouter_au_panier', function(){
var table = $('#pdr_table').DataTable();
console.log( table.row( this ).data() );
});
Upvotes: 1
Views: 676
Reputation: 2571
If you put the trigger in the <a>
tag inside the cell, you need to reference the parent cell instead of the <a>
.
$(document).on('click', '.Ajouter_au_panier', function(e){
var table = $('#pdr_table').DataTable();
console.log( table.row( $(this).closest("td") ).data() );
});
UPDATE / EDITED: To get the contents of a specific column, use the cells()
function with the row and column as params in an object. I.e. for column 2:
$(document).on('click', '.Ajouter_au_panier', function(e){
var table = $('#pdr_table').DataTable();
var rowId = table.row( $(this).closest("td") ).index();
console.log( table.cells({ row: rowId, column: 2 }).data()[0] );
});
UPDATE 2 / EDITED: If you want to get the contents of the same column where the link was clicked, you can do it like this:
$(document).on('click', '.Ajouter_au_panier', function(e){
var table = $('#pdr_table').DataTable();
var rowId = table.row( $(this).closest("td") ).index();
var colId = table.column( $(this).closest("td") ).index();
console.log( table.cells({ row: rowId, column: colId }).data()[0] );
});
Upvotes: 3