spikej
spikej

Reputation: 129

jQuery checkbox select all and change background color on select

I have a table with checkboxes in the first column, and a "select all" checkbox in the header. When I check a checkbox, I need the row color to change.

var $tbl = $('#tbl');
var $bodychk = $tbl.find('tbody input:checkbox');

$(function () {
    $bodychk.on('change', function () {
        $(this).closest('tr').toggleClass('hilite');
    });

    $tbl.find('thead input:checkbox').change(function () {
        var c = this.checked;
        $bodychk.prop('checked', c);        
    });
});
  1. If you select the individual boxes, the row changes color
  2. If you click the "select all" box, it'll toggle the other checkboxes.

But I can't get both working together. See here

These questions come close but don't fully answer what might be wrong...

Change class of tr if checkbox is selected

Jquery "select all" checkbox

Upvotes: 0

Views: 2132

Answers (2)

indubitablee
indubitablee

Reputation: 8216

something like this? http://jsfiddle.net/hb6cx0tn/9/

var $tbl = $('#tbl');
var $bodychk = $tbl.find('tbody input:checkbox');

$(function () {
    $bodychk.on('change', function () {
        if($(this).is(':checked')) {
            $(this).closest('tr').addClass('hilite');
        }
        else {
            $(this).closest('tr').removeClass('hilite');
        }
    });

    $tbl.find('thead input:checkbox').change(function () {
        var c = this.checked;
        $bodychk.prop('checked', c);
        $bodychk.trigger('change'); 
    });
});

i chose not to use toggle because it doesnt ensure that the checkbox is checked in order for the item to be highlighted.

the line $bodychk.trigger('change'); causes the .change() event to trigger so that you're just not adding a class to the element, you're actually triggering the checking of the element.

Upvotes: 1

jmore009
jmore009

Reputation: 12933

Just add the same line you had in the single checkbox:

$bodychk.prop('checked', c).closest("tr").toggleClass('hilite');        

FIDDLE

You're still locating the tbody > input:checkbox so you can still back out to the parent tr and toggle the class

Upvotes: 0

Related Questions