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-problem .btn-details').on('click', function(){
   showModalDialog(this);
});

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

Name Position Office Extn. Start date Salary
Name Position Office Extn. Start date Salary

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()

So the code below works only for the first page elements because elements from other pages were not available in DOM at the time the code was executed.

$('#example-problem .btn-details').on('click', function(){
   showModalDialog(this);
});

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-problem').on('click', '.btn-details', function(){
   showModalDialog(this);
});

We attach event handler to the table '#example-problem' and specify a selector for the button '.btn-details' 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.

Name Position Office Extn. Start date Salary
Name Position Office Extn. Start date Salary

You Might 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

Leave a Reply

You may use simple HTML to add links or lists to your comment. Also use <pre><code class="language-*">...</code></pre> to mark up code snippets. We support language-js, language-markup and language-css for comments.
(Optional)

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