javascript 限制允许选中的复选框数量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14463238/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:41:07  来源:igfitidea点击:

Limit number of checkboxes allowed to be checked

javascriptjqueryforms

提问by mpdc

Possible Duplicate:
Count the number of checkboxes selected without reloading the page?

可能的重复:
计算选中的复选框的数量而不重新加载页面?

I have an order form that asks the User which type of pass they would like (1-3 days), and gives them the option to choose the days they want the pass for.

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

Currently, when they choose 3 days, my JQuery selects all 3 checkboxes for them, and deselects when they choose 1 or 2 day(s). However, what I'm trying to do is:

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

When they select 2 day pass, it only allows them to check a maximum of 2 boxes. When they select a 1 day pass, it only allows them to check 1 box.

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

I'm drawing a blank as to what needs to go in my validateDays()function - the best way to go about running this validation or whether this is actually the best route to take.

我对我的validateDays()函数中需要做的事情一无所知 - 运行此验证的最佳方法,或者这是否实际上是最佳途径。

Every method I think of using requires the checkboxes to have the same Name/ID - but due to other parts of the form (omitted), they unfortunately can't.

我想到使用的每种方法都要求复选框具有相同的名称/ID - 但由于表单的其他部分(省略),不幸的是它们不能。

Any ideas / pointers?

任何想法/指示?

HEAD Section JavaScript:

HEAD 部分 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>

BODY Section HTML:

正文部分 HTML:

<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">

采纳答案by j08691

Here's a jQuery solution: jsFiddle example

这是一个 jQuery 解决方案:jsFiddle 示例

$('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
    });
});

回答by jbabey

You need to check the number of checked boxes in your validate function:

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

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

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

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

Keep in mind that any javascript validation can be bypassed, so ensure you are performing some type of validation on your server as well.

请记住,任何 javascript 验证都可以绕过,因此请确保您也在服务器上执行某种类型的验证。

Also note you may want to change the numBoxesCheckedselector if there are other unrelated checkboxes on the page, such as limiting it to a container e.g.

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

var numBoxesChecked = $('#someContainer').find("input:checkbox:checked").length;

回答by Thomas Jones

jQuery exposes a checkbox selectorthat should prove useful here.

jQuery 公开了一个复选框选择器,在这里应该很有用。

Your validateDaysfunction can then do something along these lines

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
    }
...

However, you might have an issue with "reverting" the box. You might be able to do simply

但是,您可能会遇到“还原”框的问题。你也许可以简单地做

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

回答by Christian

You could also do it dymanically, using a function like so:

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

$('.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);
  }
});

Assuming a few small modifications to your html:

假设对您的 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">

Demo: http://jsbin.com/osecep/1/

演示:http: //jsbin.com/osecep/1/

It's not perfect, and you'd probably want to clear the checkboxes when the number of days is changed, but that should set you on the right track.

这并不完美,您可能希望在更改天数时清除复选框,但这应该使您走上正确的轨道。

回答by CollyMellon

I'm not an expert in this area by any means but here is what I do on a site of mine, you should be able to modify it to suit your needs...just remember to give your inputs the same class name.

无论如何,我不是这方面的专家,但这是我在我的网站上所做的,您应该能够修改它以满足您的需要...只需记住为您的输入提供相同的类名。

<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;
}