Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.dataTable() pagination breaks class .click responsiveness

Tags:

datatables

When I construct a normal table and give each column a distinct class, the classes are responsive for all rows. However, when I call .dataTable() on my table, only page 1 of the paginated results is responsive. Page 2 and beyond are not responsive.

Example code:

var dataTableID = 'questionsTable';

var columns = {
    questionID: "ID",
    CategoryString: "Cat",
    difficultyLevel: "Diff",
    timesAsked: "Qty",
    questionText: "Question Text"
};

// my own little function that builds the HTML table. <TD> classes are column names   
//-- eg .questionID, .CategoryString, etc
var tableHTML = makeTable(questions, columns);

$('#' + dataTableID).html(tableHTML);

// dataTable works nicely except only page 1 .click is responsive!
$('#' + dataTableID).dataTable();

// works fine if I remove .dataTable() above. ONLY works for first page of results  
// if I keep .dataTable()
$('.questionID').on("click", function() {
    alert('Click called');
});
like image 614
goldfinger Avatar asked Jan 18 '26 21:01

goldfinger


1 Answers

When using pagination, dataTables change the visible rows by moving <tr>'s back and forth the DOM. $('.questionID').on is processed for columns on the first page only, since those columns is the only visible (accessible) columns after initialization.

So you must assign the click handler (or whatever you want to attach) on page change rather than on initialization. Here by the use of the fnDrawCallback event :

function clickHandler() {
   alert('Click called');
}

var dataTable = $('#example').dataTable({
    fnDrawCallback : function() {
       $('.questionID')
        .off("click", clickHandler)
        .on("click", clickHandler)        
    }        
});

see demo -> http://jsfiddle.net/U9Jmg/

Notice the use of .off. dataTables actually moves the <tr>'s back and forth the DOM and a table in memory, including any attached events. If previous attached events is not released, we will end up in multiple alerts for each column.

Also note I have only used only one class .questionID for all the columns in the demo. The example is 1.10.x but this works in 1.9.x as well.


As you can see of the comments below, you could also use a delegated event instead of direct event binding. It changes the setup and perhaps it is not suitable for your needs, but anyway :

$('#example tbody').on('click', '.questionID', clickHandler);

see demo -> http://jsfiddle.net/L29Dq/

like image 154
davidkonrad Avatar answered Jan 21 '26 07:01

davidkonrad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!