views:

61

answers:

3

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?

A: 

you probably need to look in to event.stopPropagation - this should stop the event bubbling up to the checkbox

Simon Scarfe
There shouldn't be any "bubbling up to the checkbox" - `<input>` elements cannot, by definition, contain any child elements.
Andy E
+2  A: 

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');
    }
});
Andy E
@Andy im a jQuery/javascript beginner,i was just wondering wouldnt if(event.target.tagName=="TD") have worked here ?
manraj82
@manraj82: yes, as per the first example in my answer. I accidentally left my "TD" string as lowercase, I've fixed it now.
Andy E
A: 

this should work:

$('.scrollTable tr').click(function(event) {
    var $this = $( event.currentTarget );

    if( $this.is( 'tr' ) )
    {
        $(':checkbox', this).trigger('click');
    }
});
ovais.tariq