javascript 限制表单中的选中复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10458924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Limit checked checkbox in a form
提问by Ahmed Waheed
I have an HTML form with a set of checkboxes, how to make the user can only check a fixed number of them
我有一个带有一组复选框的 HTML 表单,如何让用户只能检查固定数量的复选框
回答by jaredhoyt
This example will count the number of checked inputs after each one is checked and compare against the maximum number allowed. If the maximum is exceeded, the remaining checkboxes are disabled.
此示例将在检查每个输入后计算已检查输入的数量,并与允许的最大数量进行比较。如果超过最大值,则其余复选框将被禁用。
jQuery(function(){
var max = 3;
var checkboxes = $('input[type="checkbox"]');
checkboxes.change(function(){
var current = checkboxes.filter(':checked').length;
checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});
});
Here is a working example - http://jsfiddle.net/jaredhoyt/Ghtbu/1/
这是一个工作示例 - http://jsfiddle.net/jaredhoyt/Ghtbu/1/
回答by Sampson
This binds to each checkbox a bit of logic that checks to see how many checkboxes are checked in the current form. If that number equals 2, we disable all other boxes.
这将一些逻辑绑定到每个复选框,检查当前表单中有多少复选框被选中。如果该数字等于 2,我们将禁用所有其他框。
$("form").on("click", ":checkbox", function(event){
$(":checkbox:not(:checked)", this.form).prop("disabled", function(){
return $(this.form).find(":checkbox:checked").length == 2;
});
});
This works on a per-form basis, meaning you can have multiple forms that don't touch the inputs of one another. In the demo below I showcase three forms, all of which contain three checkboxes. The restriction of 2 checkboxes is limited to their respective forms.
这适用于每个表单,这意味着您可以拥有多个不接触彼此输入的表单。在下面的演示中,我展示了三种表单,所有表单都包含三个复选框。2个复选框的限制仅限于它们各自的形式。