Search code examples
javascriptjquerytablesorter

Parent / Child element bindings for click event


I'm using the jQuery tablesorter - I've got checkboxes on each row and essentially want to have a "select all" checkbox inside the <th> element.

I can't actually access the click event, even after disabling the tablesorter on that specific column.

Simple JS test:

$('input[type="checkbox"].select-all').on("click", function(e){
  console.log("Clicked!");
});

Click event does nothing, which is why I'm presuming the tablesorter is binded to the parent <th> element. The header:

<tr>
  <th class="no-sort"><input type="checkbox" class="select-all" /></th>
  <th>Some Sortable title</th>
</tr>

Any ideas on how to access that child checkbox event? I have set that column to not sort via:

// Table-sort
var noSortHeaders = {};
$("table").find("th.no-sort").each( function(index, el){
  noSortHeaders[ $(this).index() ] = {sorter: false};
});
$("table").tablesorter({
    headers: noSortHeaders
});

Solution

  • If the checkbox is created after DOM ready event, you do want to use event delegation. And I would prefer the change event to the click event:

    $(document).on('change', 'input[type=checkbox].select-all', function(e) {
        console.log('Changed!');
    });
    

    Or, better still:

    $('table').on('change', 'input[type=checkbox].select-all', function(e) {
        console.log('Changed!');
    });