Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Datatables click event not working for pages except 1

I am using JQuery Datatable for my application. I have a simple code which displays all my clients and a script which fires on the click of table row. Now, the problem is, this works fine for the first page, however, for all the other pages click event on the row is not identified. Please find below the code for the datatable and the script library.

// viewAllClients.php

<table id="view_all_entries" >
    <thead>
    <tr>
        <th>Name</th>
        <th>City</th>
    </tr>
</thead>
<tbody>
    <?php 
    $values = Client::all();
    foreach ($values as $value)
        {?>
<tr class="options" data-val="{{$value->name}}" data-id="{{$value->id}}">
        <td>{{$value->name}}</td>
        <td>{{$value->city}}</td>
        </tr>
    <?php }
    ?>  
</tbody>
</table>

//default.js

$('#view_all_entries').DataTable( {
            "aaSorting": [[ 2, "desc" ]],
            "iDisplayLength": 30,
            "sPaginationType": "full_numbers"
        } );

$('#view_all_entries .options').click(function(){
var id = $(this).closest('tr').data('id');
document.location.href = $('#route_path').val()+'/'+id + '/edit';
});

Any help would really be appreciated. Thanks.

like image 536
Chintan Parekh Avatar asked Dec 26 '22 09:12

Chintan Parekh


2 Answers

So, well, based on the answer by Halcyon, I figured out that I needed a minor change for event delegation. I hope the following code helps other stucked with the same problem.

//default.js    
$('body').delegate('#view_all_entries .options', 'click', function () {
  var id = $(this).closest('tr').data('id');
  document.location.href = $('#route_path').val()+'/'+id + '/edit';
});
like image 88
Chintan Parekh Avatar answered Jan 13 '23 17:01

Chintan Parekh


$('#view_all_entries .options') matches DOM Nodes that are currently on the page. Once you go to the next page a new set of DOM Nodes is created. If you also want those to be clickable you must added the click handler.

I think there is a way to automatically do this in jQuery but the straight forward approach is to add the click handler whenever the data changes.

You can bind to the page event to know when a new page is loaded: https://datatables.net/release-datatables/examples/advanced_init/dt_events.html

It's little bit like this row callback exmaple: https://datatables.net/release-datatables/examples/advanced_init/row_callback.html

like image 39
Halcyon Avatar answered Jan 13 '23 17:01

Halcyon