【问题标题】:How to limit the number of selected checkboxes?如何限制选中复选框的数量?
【发布时间】:2013-09-30 20:43:32
【问题描述】:

我有以下 HTML:

<div class="pricing-levels-3">
   <p><strong>Which level would you like? (Select 3 Levels)</strong></p>
   <input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1<br>
   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2<br>
   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3<br>
   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4<br>
   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5<br>
   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 6<br>
   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 7<br>
</div>

现场直播:

http://www.chineselearnonline.com/amember/signup20.php

我该怎么做才能让用户只能选择其中的 3 个复选框?

【问题讨论】:

标签: jquery forms checkbox


【解决方案1】:

使用change 事件,您可以执行以下操作:

var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
   if($(this).siblings(':checked').length >= limit) {
       this.checked = false;
   }
});

See this working demo

【讨论】:

  • 我会将$(this).siblings(':checked').length 更改为$("input[name='vehicle']:checked").length; 以获得更通用的答案。仅当复选框共享相同的父元素时,您的才有效。如果它们位于不同的 &lt;li&gt;&lt;td&gt; 标记中,则情况可能并非如此。
  • @RickSmith 同意了,但是您还需要将 &gt;= limit 更改为 &gt; limit,因为您现在还要计算刚刚点击的那个。
【解决方案2】:

试试这样。

在更改事件时,

$('input[type=checkbox]').on('change', function (e) {
    if ($('input[type=checkbox]:checked').length > 3) {
        $(this).prop('checked', false);
        alert("allowed only 3");
    }
});

JSFiddle查看这个

【讨论】:

  • 如果一页中有一个复选框列表,这是最好的解决方案,感谢您的惊人回答:)
  • 我更喜欢这个答案,因为它不会将复选框限制在标签或 div 内。
【解决方案3】:

试试这个DEMO:

 $(document).ready(function () {
   $("input[name='vehicle']").change(function () {
      var maxAllowed = 3;
      var cnt = $("input[name='vehicle']:checked").length;
      if (cnt > maxAllowed) 
      {
         $(this).prop("checked", "");
         alert('Select maximum ' + maxAllowed + ' Levels!');
     }
  });
});

【讨论】:

    【解决方案4】:

    我认为我们应该使用click 而不是change

    工作DEMO

    【讨论】:

    • 那么标签绑定有问题。我认为更改事件更好。
    【解决方案5】:
    $('.checkbox').click(function(){
      if ($('.checkbox:checked').length >= 3) {
        $(".checkbox").not(":checked").attr("disabled",true);
      }
      else 
        $(".checkbox").not(":checked").removeAttr('disabled');
    });
    

    我用过这个。

    【讨论】:

    • 我认为它们比解决方案更简单和用户友好
    【解决方案6】:
    $("input:checkbox").click(function(){
        if ($("input:checkbox:checked").length > 3){
          return false;
       }
    });
    

    【讨论】:

      【解决方案7】:

      工作DEMO

      试试这个

      var theCheckboxes = $(".pricing-levels-3 input[type='checkbox']");
      theCheckboxes.click(function()
      {
          if (theCheckboxes.filter(":checked").length > 3)
              $(this).removeAttr("checked");
      });
      

      【讨论】:

        【解决方案8】:

        我想说就像 letiagoalves 说的,但您的表单中可能有多个复选框问题,所以我建议您这样做:

          var limit = 3;
            $('input.single-checkbox').on('change', function(evt) {
                if($('input.single-checkbox').siblings('input.single-checkbox:checked').length > limit) {
                    this.checked = false;
                }
            });
        

        【讨论】:

          【解决方案9】:

          这就是我的工作方式:

          // Function to check and disable checkbox
          function limit_checked( element, size ) {
            var bol = $( element + ':checked').length >= size;
            $(element).not(':checked').attr('disabled',bol);
          }
          
          // List of checkbox groups to check
          var check_elements = [
            { id: '.group1 input[type=checkbox]', size: 2 },
            { id: '.group2 input[type=checkbox]', size: 3 },
          ];
          
          // Run function for each group in list
          $(check_elements).each( function(index, element) {
            // Limit checked on window load
            $(window).load( function() {
              limit_checked( element.id, element.size );
            })
          
            // Limit checked on click
            $(element.id).click(function() {
              limit_checked( element.id, element.size );
            });
          });
          

          【讨论】:

            【解决方案10】:

            我有更改此功能以自动取消选中上一个

                  var limit = 3;
                  $('.compare_items').on('click', function(evt) {
                    index = $(this).parent('td').parent('tr').index();
                    if ($('.compare_items:checked').length >= limit) {
                      $('.compare_items').eq(localStorage.getItem('last-checked-item')).removeAttr('checked');
                      //this.checked = false;
                    }
                    localStorage.setItem('last-checked-item', index);
                  });
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
            <input type="checkbox" class="compare_items">1
            <input type="checkbox" class="compare_items">2
            <input type="checkbox" class="compare_items">3
            <input type="checkbox" class="compare_items">4
            <input type="checkbox" class="compare_items">5
            <input type="checkbox" class="compare_items">6
            <input type="checkbox" class="compare_items">7
            <input type="checkbox" class="compare_items">8
            <input type="checkbox" class="compare_items">9
            <input type="checkbox" class="compare_items">10

            【讨论】:

              【解决方案11】:

              我今天这样做了,不同之处在于我想取消选中最旧的复选框,而不是阻止用户检查新的复选框:

                  let maxCheckedArray = [];
                  let assessmentOptions = jQuery('.checkbox-fields').find('input[type="checkbox"]');
                  assessmentOptions.on('change', function() {
                      let checked = jQuery(this).prop('checked');
                      if(checked) {
                          maxCheckedArray.push(jQuery(this));
                      }
                      if(maxCheckedArray.length >= 3) {
                          let old_item = maxCheckedArray.shift();
                          old_item.prop('checked', false);
                      }
                  });
              

              【讨论】:

                【解决方案12】:

                如果您想在允许 3 个复选框的条件下取消选中您首先选择的复选框。使用香草 javascript;您需要在您的 html 输入复选框中指定 onclick = "checking(this)"

                var queue = [];
                function checking(id){
                   queue.push(id)
                   if (queue.length===3){
                    queue[0].checked = false
                    queue.shift()
                   }
                }
                

                【讨论】:

                • 我认为这可以通过检查复选框是否未点击来进一步改进,如果是,则将其从列表中删除。
                【解决方案13】:

                这个函数只是检查你是否刚刚选中了一个复选框。如果是,它将checked 值加一。如果达到限制,则拒绝下一个复选框。

                var limit = 3;
                var checked = 0;
                $('.single-checkbox').on('change', function() {
                  if($(this).is(':checked'))
                    checked = checked+1;
                
                  if($(this).is(':checked') == false)
                    checked = checked-1;
                
                  if(checked > limit) {
                    this.checked = false;
                    checked = limit;
                  }
                });
                <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
                <div class="pricing-levels-3">
                  <p><strong>Which level would you like? (Select 3 Levels)</strong></p>
                  <input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1<br>
                  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2<br>
                  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3<br>
                  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4<br>
                  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5<br>
                  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 6<br>
                  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 7<br>
                </div>

                【讨论】:

                  【解决方案14】:

                  此方法适用于容器中的复选框,例如引导复选框

                      const checkedLimmit = 2;
                  
                      function ValidateCheckBoxGroup(container) {
                  
                          if (container.find('input[type="checkbox"]:checked').length >= checkedLimmit) {
                              container.find('input[type="checkbox"]:not(:checked)').prop('disabled', true);
                              container.find('input[type="checkbox"]:not(:checked)').closest('div.checkbox').addClass('disabled');
                          } else {
                              container.find('input[type="checkbox"]:not(:checked)').prop('disabled', false);
                              container.find('input[type="checkbox"]:not(:checked)').closest('div.checkbox').removeClass('disabled');
                          }
                      }
                  
                      $(function () {
                          // validate containers on page load
                          $('div.checkbox-group').each(function () {
                              ValidateCheckBoxGroup($(this));
                          });
                  
                          // set checkbox events
                          $('div.checkbox-group input[type="checkbox"]').change(function () {
                              ValidateCheckBoxGroup($(this).closest("div.checkbox-group"));
                          });
                      });
                  

                  【讨论】:

                    猜你喜欢
                    • 2023-04-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2011-02-27
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多