Checkboxes IE7/Firefox
by tsimbalar
HTML
<div id="gridContainer">
<table id="grid">
<tr>
<th>
<input type="checkbox" id="cbSelectAll" onclick="selectAll(this);"/>
<label for="cbSelectAll">select/unselect all</label>
</th>
<th>...</th>
</tr>
<tr>
<td><input type="checkbox" name="ctn01_cbSelect" onchange="selectOneChanged(this);"/></td><td>line 1</td>
</tr>
<tr>
<td><input type="checkbox" name="ctn02_cbSelect" onchange="selectOneChanged(this);"/></td><td>line 2</td>
</tr>
<tr>
<td><input type="checkbox" name="ctn03_cbSelect" onchange="selectOneChanged(this);"/></td><td>line 3</td>
</tr>
</table>
</div>
<input type="button" id="myButton" value="save"/>
CSS
table, td, th{border:1px solid #C0C0C0;}
td, th{padding:5px;}
JavaScript
//called by checkbox in the first row of table
function selectAll(cb) {
//alert("selectAll is checked ? " + cb.checked);
//make it a jQuery object to easily access it
var $cbSelectAll = $(cb);
//go up to the containing table / grid
var $grid = $cbSelectAll.closest("table");
//is the selectAll checkbox checked ?
var shouldSelectAll = cb.checked;
var $checkboxes = $grid.find('input:checkbox[name$="_cbSelect"]');
//reset state and trigger a click to toggle state + notify events
$checkboxes.attr("checked", shouldSelectAll ? "checked" : "").change();
}
function selectOneChanged(cb) {
//check if there are other checked checkboxes
//to know whether to disable/enable button
if (cb.checked) {
//checked : the button MUST be enabled
$("input#myButton").attr("disabled", "");
}
else {
//make it a jQuery object to easily access it
var $cbSelect = $(cb);
//not checked : see if it is the other checkboxes are checked ...
//go up to the containing table / grid
var $grid = $cbSelect.closest("table");
var nb_checked_cb = $grid.find('input:checkbox[name$="_cbSelect"]:checked').length;
if (nb_checked_cb >= 1) {
//enableit
$("input#myButton").attr("disabled", "");
}
else {
//disable it
$("input#myButton").attr("disabled", "disabled");
}
}
}
$(document).ready(function() {
//disable button on first load
$("input#myButton").attr("disabled", "disabled");
$("input:checkbox").click(function(){
//hack, mostly for IE
//by default, clicking on a checkbox does not trigger change
//unfocussing the checkbox does !
$(this).blur().focus();
});
});