Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery detect which element a onClick occurs to

I'm attempting to activate table row checkbox when the user clicks within a table row. Each row has a checkbox.

I have the following code which works fine as a standard version.

$('.scrollTable tr').click(function(event) {
    if(event.target.type !== 'checkbox') {
        $(':checkbox', this).trigger('click');
    }
});

The data in the table I'm attempting to add this to has various types i.e. there are images which create popups, links which create tooltips and links which redirect to another page. The problem I'm having is that in clicking a link, image etc the corresponding checkbox is ticked.

Any ideas?


1 Answers

Propagation is the issue here. When you click an image or link, that event bubbles up through the ancestors and fires the click handler when it reaches the <tr> element. event.target will refer to the original clicked element. You should be more specific about the "type"s you allow or disallow. For example:

$('.scrollTable tr').click(function(event) {
    if(event.target.tagName == 'TD') {
        $(':checkbox', this).trigger('click');
    }
});

Example disallowing <a>, <img> and <input> using an object map:

$('.scrollTable tr').click(function(event) {
    var disallow = { "A":1, "IMG":1, "INPUT":1 }; 
    if(!disallow[event.target.tagName]) {
        $(':checkbox', this).trigger('click');
    }
});
like image 123
Andy E Avatar answered Dec 23 '25 08:12

Andy E