如果用户在正确的序列中选择了25个复选框中的8个,我一直在处理允许进入我网站某个部分的页面。
以下是我迄今为止所做的工作CLICK HERE TO SEE A LIVE VERSION
我的问题是,如何在选择8之后完全禁用其余的复选框,到目前为止我使用javascript来计算,我有一个警告弹出窗口让他们不再选择,但我想如果可能的话,完全禁用其余的复选框。
答案 0 :(得分:3)
我简化了您的代码,它是here。
这将回答你的问题,
//update checkCount
checkCount = $(':checked').length;
if (checkCount >= maxChecks) {
//alert('you may only choose up to ' + maxChecks + ' options');
$(':checkbox[name=checkbox]').not(':checked').attr('disabled', true);
} else {
$(':checkbox[name=checkbox]:disabled').attr('disabled', false);
}
答案 1 :(得分:0)
您可以通过修改setChecks
方法来执行此操作,如下所示:
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;
}
}
与手头的问题无关,但希望有用:我知道这是一个简单的例子,因此可能并不代表你的实际代码,但是你应该考虑使用一致的格式,特别是在缩进方面(在较小程度上)间距)。此外,在编写javascript时总是使用分号是个好习惯,即使它们有时是可选的。可读代码更容易调试,扩展,并且更容易让其他人理解。
您可以做的另一件事就是使用样式表,而不是在每个td
元素中指定宽度和对齐,并在每个复选框中使用不显眼的javascript而不是onclick
事件。这些都可以在document.ready
事件中用简单的jQuery绑定语句替换:
$('table input:checkbox').click(setChecks);
这需要修改setChecks
来接收事件参数。 (编辑)像这样:
function setChecks() {
if(this.checked) {
...
} else { ... }
}
您实际上并不需要事件参数,因为this
指的是当前事件目标,因此您可以完全删除该参数。
答案 2 :(得分:0)
现在你有了警告,请使用jQuery的这一点:
$('input[name=checkbox]:not(:checked)').attr('disabled','disabled');
通过以下方式查看代码的分支:http://jsfiddle.net/fKwEQ/