Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a onclick function on every Datatable Table tr? [duplicate]

I am using datatable using ajax calling and the script for datatable is like -

$(document).ready(function() {
    $('#example').DataTable({
        "columns": [
            { "data": "name" },
            { "data": "position" },
            { "data": "salary" }
        ]
    });
});

and every row is showing like - "<tr role="row" class="even">"

But i need to put a onlcick function every datatable rows like - "<tr ondblclick="getDetails(id)" role="row" class="even">"

so how can i do that any suggestion ?

Thanks in advance.

like image 368
Rifat Tanjir Avatar asked Aug 31 '25 22:08

Rifat Tanjir


2 Answers

As seen at this site you can do

$('#example tbody').on('click', 'tr', function () {
    var data = table.row( this ).data();
    alert( 'You clicked on '+data[0]+'\'s row' );
} );

or dblclick

$('#example tbody').on('dblclick', 'tr', function () {
    var data = table.row( this ).data();
    alert( 'You double clicked on '+data[0]+'\'s row' );
} );
like image 116
D. Seah Avatar answered Sep 03 '25 13:09

D. Seah


you can make a jquery on click event on the class "even".. But to recieve an ID you will need to have either an id or a data-id on each row to know which id you want to use..

<tr role="row" class="even" data-id="1">
<tr role="row" class="even" data-id="2">

$(".even, .odd").on("click", function() {
   var id = $(this).data("id); or $(this).id(); // need to check what rowId does
   alert("test"); or alert(id);
   getDetails(id);
});

you can set an id by doing something like this:

$('#example').DataTable({
    "columns": [
        { "data": "name" },
        { "data": "position" },
        { "data": "salary" }
    ],
    rowId: 'staffId' //staffID has to be given from you
});
like image 44
Christopher Supertramp Avatar answered Sep 03 '25 12:09

Christopher Supertramp