Clickable Row & Checkbox conflict
Asked Answered
M

5

22

I made my table row clickable with this function

    $("#grid tbody tr").click(function () {
    var $checkbox = $(this).find(':checkbox');
    $checkbox.attr('checked', !$checkbox.attr('checked'));
});

and it works fine, however when I try to click the checkbox self, it doesnt work. What should I do to make both of them work?

Mandeville answered 18/4, 2011 at 10:7 Comment(3)
I try to click the checkbox self??? meansScyphozoan
why do you need to override the default browser function??Unintelligent
He wants to make clicking the row toggle the checkbox. Basically like a huge label.Hooke
G
35

Using a single event handler:

$("#grid tbody tr").click(function(e) {
    if (e.target.type == "checkbox") {

        // stop the bubbling to prevent firing the row's click event
        e.stopPropagation();
    } else {
        var $checkbox = $(this).find(':checkbox');
        $checkbox.attr('checked', !$checkbox.attr('checked'));
    }
});

http://jsfiddle.net/karim79/UX2Fv/

Graniah answered 18/4, 2011 at 10:16 Comment(2)
is it possible to leave 1 checkbox always selected? I dont want to toggle the last checkbox http://jsfiddle.net/uPqXf/Mandeville
For newer jQuery use the prop attribute: $checkbox.prop('checked', !$checkbox.prop('checked')); attr may fail.Parole
H
5
$('#grid tbody tr input:checkbox').click(function(e) {
    e.stopPropagation();
});

Then clicking the checkbox will not trigger a click event on the tr.

Hooke answered 18/4, 2011 at 10:15 Comment(1)
is it possible to leave 1 checkbox always selected? I dont want to toggle the last checkbox http://jsfiddle.net/uPqXf/Mandeville
S
3

better u can do this with simple HTML, write for attribute in label

<input type="checkbox" id="myCheck"><label for="myCheck">CheckThis</label>
                              ^                   ^

Note: id of <input type="checkbox" would be value of for attribute in <label>

DEMO

Scyphozoan answered 18/4, 2011 at 10:18 Comment(4)
how to you put that ^ below text??Unintelligent
@experimentX simple: SHIFT+6Scyphozoan
hmmm also very useful and simpleMandeville
This doesn't make the entire row clickable, only the label text.Tobar
T
0

These answers all work fine, but I was stuck for a long while trying to figure out why I couldn't get them to work. I was generating my table rows dynamically and they didn't exist on the DOM yet. For this reason, none of the solutions worked.

What solved this for me was to use the on() method.

$('body').on('click', '#grid tbody  tr', function (e) {
Tobar answered 17/9, 2015 at 1:38 Comment(0)
S
0

Try this

$('#grid tbody tr input:checked').click(function(e) {
    e.stopPropagation();
});
Stretcherbearer answered 10/9, 2016 at 8:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.