2

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');
    }
});
2
  • Just checking, have you only got 1 checkbox in that row? Commented Dec 25, 2009 at 21:37
  • Yep it's just the one checkbox. The row is either checked or unchecked. Commented Dec 26, 2009 at 4:08

2 Answers 2

2

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');
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.