2

I'm using jQuery DataTables and I have a table which is generated using a foreach loop. In each row generated, 2 buttons are made with a different number added to a data attribute.

After the page loads, dataTables kicks in and renders the table. I have an onClick handler that responds to the buttons when clicked.

However, when I sort table columns that dataTables is capable of doing, the buttons simply do not respond to the onClick handler.

What can I do to prevent dataTables from causing the buttons to do nothing when either of the sorting columns are used?

1
  • Does this happen on all browsers? Commented May 31, 2015 at 18:20

2 Answers 2

1

Do not use $('.button').click, because those buttons are recreated when sorted, instead use on jquery event

$(document).on('click', '.button',function(){
  //your code
});
Sign up to request clarification or add additional context in comments.

4 Comments

This doesn't work. I'd like to mention I made a big change to my code. Instead of a foreach now, all the table row content is generated using DataTable's ajax option. The ajax PHP code generates the HTML buttons that loads into the table.
there is no way that this code doesn't works, use your selector, e.g. if your buttons got a class "test" then instead '.button' add '.test'
Your code is incorrect because jQuery on() function requires parameters in the following order: event, selector, handler. Besides attaching event to document element is error prone, it's better to narrow it to table body, like $('#example tbody').
thnx for letting me know.
1

You need to use delegated event handlers because your buttons most likely get recreated when table is redrawn.

Below is a sample code that you need to update to match your structure:

$('#example tbody').on('click', '.button', function(e){
   // your code
});

Replace example with ID attribute of your table and replace .button with appropriate CSS selector for your buttons.

See jQuery DataTables – Why click event handler does not work for more information.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.