Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kdarty/c8444ca4b269f8df406ceb9a9c8a4339 to your computer and use it in GitHub Desktop.
Save kdarty/c8444ca4b269f8df406ceb9a9c8a4339 to your computer and use it in GitHub Desktop.
I had run into an issue where buttons used within a FooTable would only work on the first "page" and when a user clicked a "page" button to bring up more data, the same buttons would not work on the "new" data. The following solution was presented to solve the same problem when using the DataTables plugin but the same method works well for FooTa…

jQuery DataTables: Why click event handler does not work

Source: jQuery DataTables: Why click event handler does not work
Author: Michael Ryvkin

You may need to handle clicks or other events in a table powered by jQuery DataTables or the FooTable plug-in. However if the event handler is attached incorrectly, it will not be called for pages other than first or when the table is sorted or filtered.

This is one of the most common problems users have with jQuery DataTables or FooTable 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.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment