javascripthtmldatatablespagination

click event in js datatables (broken with paging)


I want to have a button with js click in each datatable row, but my code is broken by datatables paging system - default datatable option. Click works only on first datatable page. My only idea is to disable paging and create scrolable datatable, but I would prefer to keep paging for better UX.

Example datatable:

<table id="data_tables">
<thead>
    <tr>
        <td>Action</td>
        <td>Name</td>
        <td>Surname</td>
    <tr>      
</thead>
<tbody>
    <!-- Datarow 1 -->
    <tr>
        <td><input type='button' class='my_button' data-id='1' value='click' /></td>
        <td>John</td>
        <td>Wayne</td>
    </tr>
    <!-- Datarow 2 -->      
    <tr>
        <td><input type='button' class='my_button' data-id='2' value='click' /></td>
        <td>Clark</td>
        <td>Kent</td>
    </tr>
</tbody>
</table> 

Click event handler

//simple on() in jquery would do the trick in normal <table>
$( ".my_button" ).on( "click", function() {
    var id = $(this).attr("data-id");
    alert(id); 
});     

Is there a way to workaround this problem? Or maybe datatable api solution?


Solution

  • You can do something like this:

    $("#data_tables").on("click", ".my_button", function() {
        var id = $(this).data("id");
        alert(id);
    });