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. I tried this code but i run into a problem with multiple buttons.

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

    If I click any of the button first time, button will do fine but after I click any of the button again, the button will trigger 2 times and it will keep adding and adding when I click it.

    but if I add .off(), the first 2 of the buttons will do nothing. Only the last button will execute the code.

    are there any solutions to this? Thanks.

Leave a Reply to Fiqy Cancel reply

(optional)

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