Question

As the title suggests, I want to be able to click on a table td OR the checkbox itself to toggle a checkbox on or off. The solution below works when clicking on the td, but for some reason when you click on the checkbox nothing happens. Any ideas as to what is going on here?

$('td').click(function (e) {
    // Toggle checkbox
    $('input:checkbox', this).prop('checked', function (i, value) {
        return !value;
    });
});

Thanks!

http://jsfiddle.net/Littlebob/56CnR/

Was it helpful?

Solution

It's because the <input> checkbox is inside the <td> and you have attached click event to the <td>

to overcome this, Check for the target type and if it's not input checkbox, you need to process it.

DEMO

$('td').click(function (event) {
    if (!$(event.target).is('input')) {
       $('input:checkbox', this).prop('checked', function (i, value) {
        return !value;
       });
    }
});

refer

event.target

jQuery.is()

OTHER TIPS

I don't know the context of your code, but you really shouldn't need any jQuery/JavaScript here. This can be done simply with the addition of the label element:

HTML

<table>
    <tr>
        <td>
            <label><input type="checkbox" name="something" value="0"/></label>
        </td>
    </tr>
</table>

CSS

td {
    background-color: #eee;
}

label {
    padding: 20px;
    cursor: pointer;
    display: block;
}

See the demo

$(document).ready(function () {
$(document).on('click', 'tbody td', function (e) {
    e.stopPropagation();
    var checked= $(this).find('input[type="checkbox"]');
    checked.prop('checked', !checked.is(':checked'));
    $(this).toggleClass('selected'); // or anything else for highlighting purpose
});
$(document).on('click', 'input[type="checkbox"]', function (e) {
    e.stopPropagation();
    $(this).parent().toggleClass('selected'); // or anything else for highlighting purpose
});
});

check this JSFiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top