Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ID in datatables when the corresponding button is clicked

I am using Datatables and Jquery to build my application. I am fetching data into the table from my server. The table has 3 columns, each representing consignmentID, ConsignmentName and a button "Add". I want to retrieve the consigmentID of the corresponding Add button clicked.

var oTable = $('#viewAllConsignments').DataTable( {
                "aaSorting": [ ], // Prevent initial sorting
                "sAjaxSource": "getConsignment",
                "sAjaxDataProp": "",
                "sServerMethod" : "POST",
                "bProcessing": true,
                 "aoColumns": [
                        { "mData": "consignment.consignmentId"},
                        { "mData": "consignment.consignmentName" },
                        { "mData": "consignment.consignmentId",
                          "bSortable": false, 
                          "mRender": function(data, type, full) {
                                    return '<button type="button" id="btn-packets" class="btn btn-success btn-packets">Add</button>';
                            }
                        }
                ]


        });
like image 342
vkm Avatar asked Jan 30 '26 02:01

vkm


1 Answers

Dont ever use duplicated id's - id="btn-packets" - you are fine with the .btn-packets class.

Why not store consignment.consignmentId (==data) as a data-attribute on the button itself?

...
mRender: function(data, type, full) {
   return '<button data-consignmentId="'+data+'" class="btn btn-success btn-packets">Add</button>';
}
...

onclick :

$('#viewAllConsignments').on('click', '.btn-packets', function() {
    alert($(this).data('consignmentid'));
})

Good old attr() can be used too :

return '<button consignmentId="'+data+'" class="btn btn-success btn-packets">Add</button>';
alert($(this).attr('consignmentId'));

Save the whole JSON for the row as data :

return "<button data-row='"+JSON.stringify(full)+"' class='btn btn-success btn-packets'>Add</button>";

Notice I have swapped the usage of ' and ". stringify returns a string using ".

now data('row') holds the entire object you can access right away in the click handler. Even if data is inserted as string, it will return the valid JSON :

alert($(this).data('row').consignment.consignmentName);

It would be easier if we could assign the data without stringify(); data() is meant to be able to hold objects - but something like $(result).data('row', full) will not work since the rendered button not is part of the DOM at the time it is returned from mRender, it is just a plain string.

like image 104
davidkonrad Avatar answered Feb 01 '26 16:02

davidkonrad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!