Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .on() tr click event using .not() on tr checkbox click?

So my title may be confusing, but it has the right details. I have a table with clickable rows. When clicking the row, the row highlights. The table also has a checkbox column. Clicking the checkbox should NOT highlight or remove highlight from the row. How can I properly use .not() or :not in the .on('click', 'tr', function(){ ... }) ? http://jsfiddle.net/vmu0p2oe/

$('table').on('click', 'tr', function () {
                if ($(this).hasClass('selected')) {
                    $(this).removeClass('selected');
                    //$(this).find(":checkbox").prop("checked", false);
                }
                else {
                    $('tr.selected').removeClass('selected');
                    $(this).addClass('selected');
                    //$(this).find(":checkbox").prop("checked", true);
                }

            });
like image 624
triplethreat77 Avatar asked Aug 27 '14 16:08

triplethreat77


2 Answers

Add this to the beginning of the handler:

if($(e.target).is('input[type=checkbox]')) {
    return;
}

This will stop the handler from running if the element clicked is a checkbox.

Fiddle: http://jsfiddle.net/vmu0p2oe/1/

like image 139
tcooc Avatar answered Oct 20 '22 01:10

tcooc


Add a handler for the checkbox that uses stopPropagation() to prevent the click from bubbling out to the tr:

$('table').on('click', ':checkbox', function(e) {
    e.stopPropagation();
});

DEMO

like image 21
Barmar Avatar answered Oct 19 '22 23:10

Barmar