Search code examples
javascriptjquerycheckboxclicklive

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);
                }

            });

Solution

  • 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/