user189356
user189356

Reputation:

Simple jQuery Checkbox Code for Row Select

This code is meant to do the simple task of:

a) Checking the checkbox that exists in the table's <tr> row.

b) Adding the "selected" class to the <tr> row.

While it does B without problem, I cannot get it to do A. I have tried every type of jQuery selector including input[name='checked_136'], 'input.action_items', etc. and I just can't get it to mark it as checked. I've also tried used thing attr('checked',true) to check it but that doesn't make a difference.

Does anyone have some insight?

$('table.dataset tbody tr').click(function () {
    var this_row = $(this);
    var checkbox = $(this).children('input.action_items');

    if (checkbox) {
        this_row.children(':checkbox').trigger('click');
        this_row.addClass('selected');
    }
});

Upvotes: 2

Views: 1411

Answers (2)

Tomas Aschan
Tomas Aschan

Reputation: 60564

I'd do it the other way around - trigger the event on click of the checkbox instead:

$('table.dataset tbody tr :checkbox').click(function() {
    $(this).closest('tr').addClass('selected');
});

This way, you won't have to trigger the click event. Also, don't forget to wrap this in $(function() { ... }); and use .live('click', ...) instead of .click(...) if you're fetching the table with AJAX.

Update:
Since the original answer was authored, .live() has been deprectated and replaced by .on().

Upvotes: 0

brianng
brianng

Reputation: 5820

Using .children() will only get the immediate children (td's, in this case), so it's probably not finding the checkbox.

Try switching it to .find():

$('table.dataset tbody tr').click(function () {
    var this_row = $(this);
    var checkbox = this_row.find('input.action_items');

    if (checkbox.length > 0) {
        checkbox.attr('checked', true);
        this_row.addClass('selected');
    }
});

Upvotes: 2

Related Questions