javascript 限制选中的复选框数

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

Limit Number of Checkboxes Checked

javascriptjqueryforms

提问by L84

I have a form with several checkboxes. I have three categories of checkboxes in the form. I need to limit to a max of three checkboxes percategory.

我有一个带有多个复选框的表单。我在表单中有三类复选框。我需要限制每个类别最多三个复选框。

I used this script but it limits to three checkboxes per form.

我使用了这个脚本,但它限制为每个表单三个复选框。

jQuery(function(){
   var max = 3;
   var checkboxes = jQuery('input[type="checkbox"]');

   checkboxes.change(function(){
      var current = checkboxes.filter(':checked').length;
       checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
   });
});

How do I modify the above script to limit three checkboxes per category within one form?

如何修改上述脚本以在一个表单中限制每个类别的三个复选框?

HTML Example:

HTML 示例:

<!-- FORM CODE --> 

<!-- Start Categories -->

<label>Cat 1</label>
  <!-- Checkboxes for Cat 1 - Max of Three in Category -->
  <input type="checkbox" value="Option 1" id="CAT_Custom_365571_0" name="CAT_Custom_365571" />Creative<br />
  <input type="checkbox" value="Option 2" id="CAT_Custom_365571_1" name="CAT_Custom_365571" />Euphoric<br />
  <input type="checkbox" value="Option 3" id="CAT_Custom_365571_2" name="CAT_Custom_365571" />Uplifted<br />
  <!-- More checkboxes -->
<label>Cat 2</label>
  <!-- Checkboxes for Cat 2 - Max of Three in Category -->
  <input type="checkbox" value="Option 1" id="CAT_Custom_365572_0" name="CAT_Custom_365572" />Option 1<br />
  <input type="checkbox" value="Option 2" id="CAT_Custom_365572_1" name="CAT_Custom_365572" />Option 2<br />
  <input type="checkbox" value="Option 3" id="CAT_Custom_365572_2" name="CAT_Custom_365572" />Option 3<br />
  <!-- More checkboxes -->
<label>Cat 3</label>
  <!-- Checkboxes for Cat 3 - Max of Three in Category -->
  <input type="checkbox" value="Option 1" id="CAT_Custom_365573_0" name="CAT_Custom_365573" />Option 1<br />
  <input type="checkbox" value="Option 2" id="CAT_Custom_365573_1" name="CAT_Custom_365573" />Option 2<br />
  <input type="checkbox" value="Option 3" id="CAT_Custom_365573_2" name="CAT_Custom_365573" />Option 3<br />
  <!-- More checkboxes -->

<!-- MORE FORM CODE -->

Note: The CAT_Custom_365571_2etc is generated by the CMS I use.

注意:CAT_Custom_365571_2etc 是由我使用的 CMS 生成的。

回答by Arun P Johny

Try (if your markup matches the one in the fiddle)

尝试(如果您的标记与小提琴中的标记匹配)

jQuery(function(){
    var max = 3;
    var checkboxes = jQuery('input[type="checkbox"]');

    checkboxes.click(function(){
        var $this = $(this);
        var set = $this.add($this.prevUntil('label')).add($this.nextUntil(':not(:checkbox)'));
        var current = set.filter(':checked').length;
        return current <= max;
    });
});

Demo: Fiddle

演示:小提琴

Update:
Since you have a name for the checkboxes

更新:
因为您有复选框的名称

jQuery(function(){
    var max = 3;
    var checkboxes = jQuery('input[type="checkbox"]');

    checkboxes.click(function(){
        var $this = $(this);
        var set = checkboxes.filter('[name="'+ this.name +'"]')
        var current = set.filter(':checked').length;
        return current <= max;
    });
});

Demo: Fiddle

演示:小提琴

回答by softsdev

jQUERY

查询

$("input[name=chk]").change(function(){
    var max= 3;
    if( $("input[name=chk]:checked").length == max ){
        $("input[name=chk]").attr('disabled', 'disabled');
        $("input[name=chk]:checked").removeAttr('disabled');
    }else{
         $("input[name=chk]").removeAttr('disabled');
    }
});

HTML

HTML

<input type="checkbox" name"chk" value="A"/>A
<input type="checkbox" name"chk" value="B"/>B
<input type="checkbox" name"chk" value="C"/>C
<input type="checkbox" name"chk" value="D"/>D
<input type="checkbox" name"chk" value="E"/>E
<input type="checkbox" name"chk" value="F"/>F
<input type="checkbox" name"chk" value="F"/>G

FIDDLE EXAMPLE IS HERE

小提琴示例在这里

回答by kennypu

just add a class to all the related check boxes, and just use the class selector when checking the checkboxes for a category. eg:

只需将一个类添加到所有相关的复选框,并在检查类别的复选框时使用类选择器。例如:

HTML

HTML

<label>Cat 1</label>
<input type='checkbox' class='cat1' />
<input type='checkbox' class='cat1' />
<input type='checkbox' class='cat1' />

<label>Cat 2</label>
<input type='checkbox' class='cat2' />
<input type='checkbox' class='cat2' />
<input type='checkbox' class='cat2' />
...

JS

JS

jQuery(function(){
   var max = 3;

   var cat1_checkboxes = jQuery('input.cat1[type="checkbox"]');
   var cat2_checkboxes = jQuery('input.cat2[type="checkbox"]');
   var cat3_checkboxes = jQuery('input.cat3[type="checkbox"]');


   cat1_checkboxes.change(function(){
      var current = cat1_checkboxes.filter(':checked').length;
       checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
   });

   cat2_checkboxes.change(function(){
      var current = cat2_checkboxes.filter(':checked').length;
       checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
   });

   cat3_checkboxes.change(function(){
      var current = cat3_checkboxes.filter(':checked').length;
       checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
   });

});

回答by karaxuna

Try this:

试试这个:

jQuery(function(){
   var max = 3;
   var categories = jQuery('label'); // use better selector for categories

   categories.each(function(){
       var checkboxes = $(this).find('input[type="checkbox"]');
       checkboxes.change(function(){
            var current = checkboxes.filter(':checked').length;
            checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
        });
   });
});

回答by Tarsierseyesmaykill

This is a newbie code with javascript. It's like working...hardly... I call this function on each input. But there is surely a way to call this function one time. It's working but uncheking a random checkbox from thoses who call it.

这是一个带有 javascript的新手代码。这就像工作......几乎......我在每个输入上调用这个函数。但是肯定有一种方法可以一次性调用这个函数。它正在工作,但从调用它的人那里取消选中一个随机复选框。

   <input type="checkBox"  name="cat1" value="education" onClick="just2cat();">Education
    <input type="checkBox"  name="cat2" value="faith" onClick="just2cat();">Religions
    <input type="checkBox"  name="cat3" value="news" onClick="just2cat();">News



  function just2cat()
        {
            var allInp = document.getElementsByTagName('input');
            const MAX_CHECK_ = 2; /*How many checkbox could be checked*/
            var nbChk =0;
            for(var i= 0; i<allInp.length; i++)
            {
                if(allInp[i].type.toLowerCase()=='checkbox' && allInp[i].checked) /*OR
                if(allInp[i].type.toLowerCase()=='checkbox' && allInp[i].checked===true) */
                {
                    nbChk++;

                    if(nbChk > MAX_CHECK_) 
                    {
                        alert("At most 2 categories can be chosen");
                        allInp[i].checked=false; /* try to Unchek the current checkbox :'(  */
                    }

                }
            }
        }