jQuery DataTables: Why click event handler does not work

This is one of the most common problems users have with jQuery DataTables plug-in and it has very simple solution if you understand why it occurs.

Problem

Table below demonstrates the problem with attaching event handlers incorrectly. Clicking on “Edit” button should open a modal dialog.

Event handler is attached as follows:


$('#example .btn-edit').on('click', function(){
   // ...
});

However if you go to a different page, sort or filter the table, “Edit” button stops working for those records that were previously hidden.

Cause

After the table is initialized, only visible rows exist in Document Object Model (DOM). According to jQuery on() documentation:

Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on()

Our code above worked only for the first page elements because elements from other pages were not available in DOM at the time the code was executed.

Solution

The solution is to use event delegation by providing selector for target element as a second argument in on() call, see example below. According to jQuery on() documentation:

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.


$('#example').on('click', '.btn-edit', function(){
   // ...
});

We attach event handler to the table '#example' and specify a selector for the button '.btn-edit' as an additional parameter for on() method. Event handler will now be called for all buttons whether they exist in DOM now or added at a later time.

Table below demonstrates the working solution.

You May Also Like

Comments

  1. Hi , thanks for the tutorial , I have an issue though ..

    I have attached an event handler to my table and selector is a checkbox …. but anytime the checkbox is clicked , the event handler is fired multiple times . How do I prevent the event handler from being fired multiple times.

     $('.table').on('change'  ,'.table-checkbox' , function(e){
                     
                     if($(this).prop("checked") == true)
                      {
                           //When select all is checked , items in rows_selected are duplicated / fired multiple times
                            console.log(rows_selected)
                    }
                       else
                    {
                        console.log("empty")
                      }
                        
                  });
    
  2. Hi,

    I’m a beginner, I have googled but could not find what I wanted,

    I am looking for code example Ajax sourced, client side, since we might not have more than 10k rows.

    Add, view, edit bootstrap modal,

    Once data inserted, edited ,
    refresh data table,

    Could you give me code example

    In php

  3. Hi ,

    Thanks for the tutorial , I am facing the exact same issue as mentioned in the tutorial i.e event not triggering for second page

    $(‘form[name=”showModuleDetail”] img’).on(‘click’,moduleImageClickHandler);

    I am new to this, can you help me with the problem

  4. I have a similar situation, however on PostBack, I want to programatically click an item in the list. This works fine for the first 10 (visible) items, but not for any items on page 2. The function is not firing.

    $('#widThirdPartyVendorReports').on('click', '.load-third-party-vendor-report-details', function (e) {
    
  5. Supb it’s also help full in my case also. i was facing same issue that 2nd page element not fire the event but now it’s working good..

    Thank you so much guys.

  6. hello sir,
    i want to develope multiple select option and single select option using select tag using javaScript, when i try to both selected option values in a row of table, how can i do it? please help me. as soon as possible.
    thanks

  7. Hi There,
    I have situation where I want to use the “sPaginationType”:”simple” but I need to trap Previous and Next button event to execute my custom code for business requirement.
    Can you please help.

    Regards,

  8. Many many thanks for this. I read the same concept on the datatables website and it went right over my head. Your example was concise and just what I was looking for.

    Thank you!

  9. I have similar problem when attaching click event on row to display modal dialog like this

    $("#dtable").on('click', 'tr', function () {
         var tr = $(this).closest('tr');
         var row = dtable.row( tr );
         console.log(row.data().outlet_name);
         showModal();
    });
    

    It works only at first time after loading, when I change the sort or load with different data, the console.log show undefined.
    Any clue about this? Thanks.

Leave a Reply to Anup Cancel reply

(optional)

This site uses Akismet to reduce spam. Learn how your comment data is processed.