簡體   English   中英

如何限制選中復選框的數量?

[英]How to limit the number of selected checkboxes?

我有以下 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

我該怎么做才能使用戶只能 select 3 個復選框?

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

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

看到這個工作演示

像這樣嘗試。

在更改事件中,

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

JSFiddle 中檢查這個

試試這個演示

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

我認為我們應該使用click而不是change

工作演示

$('.checkbox').click(function(){
  if ($('.checkbox:checked').length >= 3) {
    $(".checkbox").not(":checked").attr("disabled",true);
  }
  else 
    $(".checkbox").not(":checked").removeAttr('disabled');
});

我用過這個。

$("input:checkbox").click(function(){
    if ($("input:checkbox:checked").length > 3){
      return false;
   }
});

工作演示

嘗試這個

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

我會說就像 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;
        }
    });

這就是我讓它工作的方式:

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

我有更改此功能以自動取消選中以前的

 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

我今天這樣做了,不同之處在於我想取消選中最舊的復選框,而不是阻止用戶檢查新的復選框:

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

如果您想在允許 3 個復選框的情況下取消選中您首先選中的復選框。 使用香草 javascript; 您需要在 html 輸入復選框中分配 onclick = "checking(this)"

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

此功能只是檢查您是否剛剛選中了一個復選框。 如果是,它將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>

此方法適用於容器中的復選框,例如引導復選框

    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"));
        });
    });
(function ($) {
  $(document).ready(function () {
    $(document).on("change", ".pricing-levels-3 input", function () {
      var numberOfChecked = $(".pricing-levels-3 input:checkbox:checked").length;
      if (numberOfChecked >= 2) {
        $(".pricing-levels-3 input:not(:checked)").prop("disabled", true);
      } else {
        $(".pricing-levels-3 input:not(:checked)").removeAttr("disabled", true);
      }
    });
  });
})(jQuery);

這適用於我的復選框名稱。

<script>
    // limit checkbox select
    $('input[name=vehicle]').on('change', function (e) {
    if ($('input[name=vehicle]:checked').length > 3) {
        $(this).prop('checked', false);
        alert("allowed only 3");
    }
});
</script>

JS 和 HTML這對我有用,它的作用是,onclick function checkControl()將計算復選框被單擊的次數超過 3 次顯示錯誤消息。

 function checkboxControl(j) { var total = 0; var elem = document.getElementsByClassName("checkbox"); var error = document.getElementById("error"); for (var i = 0; i < elem.length; i++) { if (elem[i].checked == true) { total = total + 1; } if (total > 3) { error.textContent = "You Must Select at Least 3"; elem[j].checked = false; return false; } } }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width. initial-scale=1:0" /> <title>Document</title> </head> <body> <form action=""> <span id="error" style="color: red"></span> <br> <span>Python</span> <input type="checkbox" class="checkbox" name="interest[]" onclick="checkboxControl(0)" id="1" /> <br> <span>Javascript</span> <input type="checkbox" class="checkbox" name="interest[]" onclick="checkboxControl(1)" id="1" /><br> <span>Go</span> <input type="checkbox" class="checkbox" name="interest[]" onclick="checkboxControl(2)" id="1" /><br> <span>Laravel</span> <input type="checkbox" class="checkbox" name="interest[]" onclick="checkboxControl(3)" id="1" /> </form> </body> </html>

這些資源幫助我理解了 https://www.plus2net.com/javascript_tutorial/checkbox-limit-demo2.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM