table selected
by Ying Chor Ding
HTML
<table id="my-table">
<tr>
<th>
<input type="checkbox" class="checkall" />
</th>
<th>Items</th>
</tr>
<tr>
<td>
<input type="checkbox" class="checkboxes" />
</td>
<td>Something</td>
</tr>
<tr>
<td>
<input type="checkbox" class="checkboxes" />
</td>
<td>Something</td>
</tr>
<tr>
<td>
<input type="checkbox" class="checkboxes" />
</td>
<td>Something</td>
</tr>
</table>
Total: <span class="counted">0</span>
CSS
body { font-family: arial}
table tr th {
background: green;
}
table tr th,
table tr td {
border-bottom: 1px solid #ddd;
}
table tr.selected {
background: red;
}
JavaScript
$(document).ready(function () {
// cache element for better performance and less typing
var rows = $('#my-table > tbody').children();
// Count Checkboxes
var $checkboxes = $('.checkboxes');
var checkall = $('.checkall:checked');
$checkboxes.change(function () {
var count = $checkboxes.filter(':checked').length;
$('.counted').text(count);
});
// Select all checkboxes
$('.checkall').click(function (event) {
$('.checkboxes').prop('checked', this.checked);
var $checkboxes = $('.checkboxes');
var count = $checkboxes.filter(':checked').length;
$('.counted').text(count);
// loop through all rows. Skip 0, start from 1 cause we don't need to touch table headers
for(var i=1; i<rows.length; i++) {
var row = $(rows[i]);
// verify checkall state
event.currentTarget.checked ?
row.addClass('selected') :
row.removeClass('selected');
}
});
$("#my-table input[type='checkbox']").change(function (e) {
if ($(this).is(":checked")) {
$(this).closest('tr').addClass("selected");
} else {
$(this).closest('tr').removeClass("selected");
}
});
});