Reputation: 129
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);
});
});
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
Upvotes: 0
Views: 2132
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