Javascript 限制允许选中的复选框数

Javascript 限制允许选中的复选框数,javascript,jquery,forms,Javascript,Jquery,Forms,可能重复: 我有一个订单,询问用户他们想要哪种类型的通行证(1-3天),并让他们选择他们想要通行证的日期 目前,当他们选择3天时,my JQuery会为他们选择所有3个复选框,并在他们选择1天或2天时取消选择。然而,我想做的是: 当他们选择2天通行证时,只允许他们最多选中2个框。当他们选择1天通行证时,只允许他们选中1个复选框 对于我的validateDays()函数中需要执行的操作,我还是一片空白——这是运行此验证的最佳方式,还是实际上这是最佳途径 我想使用的每个方法都要求复选框具有相同的名

可能重复:

我有一个订单,询问用户他们想要哪种类型的通行证(1-3天),并让他们选择他们想要通行证的日期

目前,当他们选择3天时,my JQuery会为他们选择所有3个复选框,并在他们选择1天或2天时取消选择。然而,我想做的是:

当他们选择2天通行证时,只允许他们最多选中2个框。当他们选择1天通行证时,只允许他们选中1个复选框

对于我的
validateDays()
函数中需要执行的操作,我还是一片空白——这是运行此验证的最佳方式,还是实际上这是最佳途径

我想使用的每个方法都要求复选框具有相同的名称/ID——但由于表单的其他部分(省略),很遗憾,它们不能

有什么想法/建议吗

标题部分JavaScript:

<script type="text/javascript">

function validateDays() {
    $('#matthewpeckham').find('input[type="checkbox"]').click(function () {
        var pass = parseInt($('input[name="other_1"]:checked').val(), 10) //1,2,3
        var days = $('#matthewpeckham').find('input[type="checkbox"]:checked').length;
        console.log(days, pass);
        if (days == pass) {
            $('#matthewpeckham').find('input[type="checkbox"]').not(':checked').prop('disabled', true);
        }
        else {
            $('#matthewpeckham').find('input[type="checkbox"]').not(':checked').prop('disabled', false);
        }
    })
    $('input[name="other_1"]').change(function () {
        $('#matthewpeckham').find('input[type="checkbox"]').prop({
            'checked': false,
            'disabled': false
        });
        if (parseInt($(this).val(), 10) == 3) $('#matthewpeckham').find('input[type="checkbox"]').prop({
            'checked': true,
            'disabled': false
        });
    });
}

</script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" ></script>

<script type="text/javascript">
$(document).ready(function() {
    jQuery('#3daypass').click(function() {
        jQuery('#other_2 , #other_3 , #other_4').prop('checked', true);
    });
    jQuery('#2daypass , #1daypass').click(function() {
        jQuery('#other_2 , #other_3 , #other_4').prop('checked', false);
    });
});

</script>
<input name="other_1" type="radio" value="3daypass" id="3daypass" onClick="validateDays();">
<input name="other_1" type="radio" value="2daypass" id="2daypass" onClick="validateDays();">
<input name="other_1" type="radio" value="1daypass" id="1daypass" onClick="validateDays();">

<input name="other_2" type="checkbox" id="other_2" value="Tues 5 Feb">
<input name="other_3" type="checkbox" id="other_3" value="Wed 6 Feb">
<input name="other_4" type="checkbox" id="other_4" value="Thurs 7 Feb">

函数validateDays(){
$('matthewpeckham')。查找('input[type=“checkbox”]”)。单击(函数(){
var pass=parseInt($('input[name=“other_1”]:checked').val(),10)//1,2,3
变量天数=$('#matthewpeckham').find('input[type=“checkbox”]:checked')。长度;
控制台日志(天,通过);
如果(天数==通过){
$('matthewpeckham').find('input[type=“checkbox”]”)。not(':checked').prop('disabled',true);
}
否则{
$('matthewpeckham').find('input[type=“checkbox”]”)。not(':checked').prop('disabled',false);
}
})
$('input[name=“other_1”]”)。更改(函数(){
$('matthewpeckham').find('input[type=“checkbox”]”).prop({
“checked”:false,
“已禁用”:false
});
if(parseInt($(this).val(),10)==3)$('matthewpeckham').find('input[type=“checkbox”]”).prop({
“选中”:true,
“已禁用”:false
});
});
}
$(文档).ready(函数(){
jQuery('#3daypass')。单击(函数(){
jQuery('other_2,'other_3,'other_4').prop('checked',true);
});
jQuery(“#2daypass,#1daypass”)。单击(函数(){
jQuery('other_2,'other_3,'other_4').prop('checked',false);
});
});
正文部分HTML:

<script type="text/javascript">

function validateDays() {
    $('#matthewpeckham').find('input[type="checkbox"]').click(function () {
        var pass = parseInt($('input[name="other_1"]:checked').val(), 10) //1,2,3
        var days = $('#matthewpeckham').find('input[type="checkbox"]:checked').length;
        console.log(days, pass);
        if (days == pass) {
            $('#matthewpeckham').find('input[type="checkbox"]').not(':checked').prop('disabled', true);
        }
        else {
            $('#matthewpeckham').find('input[type="checkbox"]').not(':checked').prop('disabled', false);
        }
    })
    $('input[name="other_1"]').change(function () {
        $('#matthewpeckham').find('input[type="checkbox"]').prop({
            'checked': false,
            'disabled': false
        });
        if (parseInt($(this).val(), 10) == 3) $('#matthewpeckham').find('input[type="checkbox"]').prop({
            'checked': true,
            'disabled': false
        });
    });
}

</script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" ></script>

<script type="text/javascript">
$(document).ready(function() {
    jQuery('#3daypass').click(function() {
        jQuery('#other_2 , #other_3 , #other_4').prop('checked', true);
    });
    jQuery('#2daypass , #1daypass').click(function() {
        jQuery('#other_2 , #other_3 , #other_4').prop('checked', false);
    });
});

</script>
<input name="other_1" type="radio" value="3daypass" id="3daypass" onClick="validateDays();">
<input name="other_1" type="radio" value="2daypass" id="2daypass" onClick="validateDays();">
<input name="other_1" type="radio" value="1daypass" id="1daypass" onClick="validateDays();">

<input name="other_2" type="checkbox" id="other_2" value="Tues 5 Feb">
<input name="other_3" type="checkbox" id="other_3" value="Wed 6 Feb">
<input name="other_4" type="checkbox" id="other_4" value="Thurs 7 Feb">

无论如何,我都不是这方面的专家,但以下是我在我的网站上所做的工作,你应该能够修改它以满足你的需要……记住给你的输入相同的类名

<script type="text/javascript">
function Check() {
    var count = 0;
    var checkBoxes = document.getElementsByClassName('chkValidation');
    for (var index = 0; index < checkBoxes.length; index++) {
        if (checkBoxes[index].type == 'checkbox') {
            if (!checkBoxes[index].disabled) {
                count = checkBoxes[index].checked ? (count + 1) : count;
            }
        }
    }
    if (count > 3) {
        alert('Question two - please select a maximum of 3 sub questions to ask.');
        return false;
    }
    return true;
} 

函数检查(){
var计数=0;
var复选框=document.getElementsByClassName('chkValidation');
对于(var index=0;index3){
提醒('问题二-请选择最多3个子问题提问');
返回false;
}
返回true;
} 

您需要检查验证功能中的复选框数:

function validateDays() {
    var numBoxesChecked = $("input:checkbox:checked").length;

    if (document.getElementById("2daypass").checked && numBoxesChecked > 2) {
        // invalid
    }

    if (document.getElementById("1daypass").checked && numBoxesChecked > 1) {
        // invalid
    }
}
请记住,任何javascript验证都可以绕过,因此请确保您也在服务器上执行某种类型的验证

另请注意,如果页面上存在其他不相关的复选框,例如将其限制为容器,则可能需要更改
numBoxesChecked
选择器

var numBoxesChecked = $('#someContainer').find("input:checkbox:checked").length;
jQuery公开了一个在这里应该被证明是有用的

然后,您的
validateDays
函数就可以按照这些思路进行操作

var checkedBoxes = jQuery(":checkbox:checked");
var numChecked = checkedBoxes.length;
...
    else if (document.getElementById("2daypass").checked) {
        if (numChecked > 2) { /*do something*/ }
    }
    else if (document.getElementById("1daypass").checked) {
        if (numChecked > 1) { /*do something*/ }
    }
    else {
        // DO NOTHING
    }
...
但是,您可能会遇到“还原”框的问题。你也许可以做得很简单

jQuery(this).prop('checked', false)

您也可以使用如下函数动态执行此操作:

$('.checkbox').on('click', function(e) {
  var num_checked = 0;

  $('.checkbox').each(function() {
    if ( $(this).prop('checked') ) num_checked++;
  });

  var max_checked = $('input[name="other_1"]:checked').val();

  if ( num_checked > max_checked ) {
    $(this).prop('checked', false);
  }
});
假设对html进行了一些小的修改:

<input name="other_1" type="radio" value="3" id="3daypass">
<input name="other_1" type="radio" value="2" id="2daypass">
<input name="other_1" type="radio" value="1" id="1daypass">

<input class="checkbox" name="other_2" type="checkbox" id="other_2" value="Tues 5 Feb">
<input class="checkbox" name="other_3" type="checkbox" id="other_3" value="Wed 6 Feb">
<input class="checkbox" name="other_4" type="checkbox" id="other_4" value="Thurs 7 Feb">

演示:


这并不完美,当天数发生变化时,您可能希望清除复选框,但这应该会使您走上正确的轨道。

这里有一个jQuery解决方案:

$('input[type="checkbox"]').click(function () {
    var pass = parseInt($('input[name="other_1"]:checked').val(), 10) //1,2,3
    var days = $('input[type="checkbox"]:checked').length;
    console.log(days, pass);
    if (days == pass) {
        $('input[type="checkbox"]').not(':checked').prop('disabled', true);
    }
})
$('input[name="other_1"]').change(function () {
    $('input[type="checkbox"]').prop({
        'checked': false,
            'disabled': false
    });
    if (parseInt($(this).val(), 10) == 3) $('input[type="checkbox"]').prop({
        'checked': true,
            'disabled': false
    });
});

您的代码工作得很好,谢谢。有没有办法删除最后选中的复选框?其他答案中建议的jQuery不起作用。@MatthewPeckham您的意思是在计算长度时忽略最后一个复选框?您可以将
not(:last)
添加到选择器:
输入:复选框:checked:not(:last)
不幸的是,还原框的最后一行似乎不起作用-还有其他想法吗?代码已在初始问题中编辑。您似乎已经有了解决方案,但要澄清-在编写此答案时,validateDaysthis变量应该是复选框之一。这似乎已经改变了。此代码将还原已勾选的框,但您的函数似乎仅用于附加事件,并且
This
关键字将在这些函数中移动。这是一个很好的方法-物理禁用框比弹出警报方便得多。我如何调整代码,使最后一个框在某些框被解锁时重新启用?你的意思是?完美的但是,我将复选框限制为仅在表单的这一部分中找到的复选框(
#matthewpeckham
),并且由于某些原因,第一次单击复选框时验证不起作用-仅在随后的时间。我是否添加了太多的
.find
s?您已将
validateDays
的内部内容替换为他描述的事件。因此,只有在validateDays被调用后,您的事件才会被绑定(并在后续调用中一次又一次地绑定)。去掉该函数,只需将事件绑定到DOM Ready上即可。