You can do this by modifying the setChecks
method as follows:
function setChecks(obj) {
if(obj.checked) {
checkCount = checkCount + 1;
//note: modify this selector to specify the actual table in question,
//of course. If this is not known beforehand (ie there are multiple
//tables of checkboxes), you can use
// $(this).closest('table').find('input:checkbox:not(:checked)')
//instead.
if(checkCount == 8)
$('table input:checkbox:not(:checked)').attr('disabled', 'disabled');
} else {
if(checkCount == 8)
$('table input:checkbox:not(:checked)').removeAttr('disabled');
checkCount = checkCount - 1;
}
}
Unrelated to the question at hand, but hopefully helpful: I know this is a jsfiddle example and thus probably not indicative of your actual code, but you should consider using consistent formatting, especially with regard to indentation (and to a lesser extent spacing). Also, it's good habit to always use semicolons when writing javascript, even though they are sometimes optional. Readable code is much easier to debug, extend, and definitely easier for others to understand.
Another thing you can do to simplify your code is use stylesheets instead of specifying width and align in every td
element, and using unobtrusive javascript instead of the onclick
event in every checkbox. Those can all be replaced by a simple jQuery bind statement in your document.ready
event:
$('table input:checkbox').click(setChecks);
This would require modifying setChecks
to receive an event parameter instead. (Edit) Like so:
function setChecks() {
if(this.checked) {
...
} else { ... }
}
You don't actually need the event parameter because this
refers to the current event target, so you can just remove that parameter altogether.