如何限制所选复选框的数量?

ale*_*nco 39 jquery

我有以下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>
Run Code Online (Sandbox Code Playgroud)

直播网站:

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

我怎么能这样做,以便用户只能选择其中3个复选框?

let*_*ves 61

Using change event you can do something like this:

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

See this working demo

  • 我将`$(this).siblings(':checked').length`更改为`$("input [name ='vehicle']:checked").length;`用于更通用的答案.仅当复选框共享相同的父元素时,才有效.如果它们位于不同的`<li>`或`<td>标签中,则可能不是这种情况. (10认同)
  • @RickSmith同意了,但是你还需要将`> = limit`更改为`> limit`,因为你现在也在计算刚刚点击的那个. (7认同)

Pra*_*een 34

Try like this.

On change event,

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

Check this in JSFiddle


cod*_*der 6

Try this 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!');
     }
  });
});
Run Code Online (Sandbox Code Playgroud)