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

3

7

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

            });
Youthful answered 27/8, 2014 at 16:8 Comment(1)
That beautiful moment when you find exactly the problem you were trying to solve.Homily
L
11

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/

Luis answered 27/8, 2014 at 16:11 Comment(0)
P
1

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

Pedestrianism answered 27/8, 2014 at 16:12 Comment(0)
J
0

How about this:

$('table').on('click', 'tr', function (e) {
  var el = e.target;
  if ( el.type !== "checkbox"){
    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);
    }
  }
});

fiddle

Jesuit answered 27/8, 2014 at 16:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.