简体   繁体   中英

Javascript not working after Datatable Filter or Paging

I am using Django ListView to display a list of invoices. I am trying to use Javascript to send updates. For example, when the invoice is paid, the user can click on the icon of the row and that invoice will be marked as paid. Everything is working well, but, I am using datatable to allow the user a secondary filtering. On page load, the javascript and call to server works fine, however, when filter or paging is used, Javascript is not picking up the row number. Just for simplicity, I test it with a alert() function - here's the html

HTML:

<table width="100%" class="table table-striped table-bordered table-hover" id="dt-invoice">
    <thead>
        <tr>
            <th></th>
            <th>Inoice Number</th>
            <th>Description</th>
            <th>Date Sent</th>
        </tr>
    </thead>
    <tbody>
    {% csrf_token %}
    {% for i in invoice %}
        <tr id="{{ i.invoice }}">
            <td><a id='id_paid-{{ i.id }}' title="I Got This!" href="#"><i class="fa fa-check fa-fw"></i></a></td>
            <td>i.invoice_number</td>
            <td>i.invoice_description</td>
            <td>i.invoice_sent_date</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

Javascript:

$(document).ready(function() {    
    $('#dt-invoice').DataTable({
        buttons: [ 'copy', 'csv', 'excel', 'pdf','print'],
        "iDisplayLength": 10,            
        "processing": true,
        responsive: true,
        "dom": '<"top pull-left" li><"top pull-right" f> <t> <"bottom pull-left" iB><"bottom pull-right" p>',
    });

    $('[id^=id_paid-]').click(function(){
        console.log("HERE")
        row = $(this).closest('tr');
        trid = row.attr("id");
       alert(trid);
    });
});    

Any ideas? Thanks in advance!

You should delegate click event to closest static container:

$('#dt-invoice').on('click', '[id^=id_paid-]', function() {
  console.log("HERE")
  row = $(this).closest('tr');
  trid = row.attr("id");
  alert(trid);
});

The reason your click event was ignored is because at time you are binding it, only available matching elements in DOM get the event bound. Datatable plugin modify the table content, removing/adding new elements on paging/filtering. By binding it to table element (the closest static one), you handle all these dynamic elements too.

[References]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM