5

I need help. I have a page that displays records in bootstrap data table. The records are displayed 10 rows per page and each row has a checkbox on the left column. What I want to do is, when user clicks on the row, it will check the checkbox and enable the button placed after the table(user has to select at least a checkbox to activate/enable the button). I already implemented this but unfortunately it only works on the first page. When user go to second page and click on the table row, the checkbox is not checked. Anyone can help me? I appreciate it much.

//disable button when no records are selected
var checkboxes = $("input[type='checkbox']");
var btn = $("#button");
btn.attr("disabled","disabled");

checkboxes.on('click', function(event) {
    if($(this).prop('checked')){
        btn.removeAttr('disabled');
    } else {
        btn.attr("disabled",!checkboxes.is(":checked"));
    }
});

//this will check the checkbox whenever user clicks the table row
$('.clickable-row').click(function (event) {
    if (event.target.type !== 'checkbox') {
        $(':checkbox', this).trigger('click');
    }
}); 
Amanda
  • 314
  • 3
  • 12
sopi
  • 85
  • 1
  • 9

1 Answers1

4

When you use DataTables with jQuery, the plugin manages the rows that appear on the page by adding and removing elements from the DOM when you switch pages. When the table loads, the only rows that exist in the DOM are those appearing on that first page.

This means that your handler is only ever added to the first page's elements and once you switch pages, those elements are removed so when you go back to page 1, those will be newly created elements with no handlers attached.

Change your code to this:

$('#some-table-id').on('click','.clickable-row', function (event) {
    if (event.target.type !== 'checkbox') {
        $(':checkbox', this).trigger('click');
    }
}); 

This is called event delegation

See also Event binding on dynamically created elements?

Community
  • 1
  • 1
Wesley Smith
  • 19,401
  • 22
  • 85
  • 133