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

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


我该怎么做,以便用户只能选择其中三个复选框?


倚天杖
浏览 608回答 3
3回答

慕尼黑5688855

使用change事件,您可以执行以下操作:var limit = 3;$('input.single-checkbox').on('change', function(evt) {&nbsp; &nbsp;if($(this).siblings(':checked').length >= limit) {&nbsp; &nbsp; &nbsp; &nbsp;this.checked = false;&nbsp; &nbsp;}});

杨魅力

尝试这样。在变更事件中,$('input[type=checkbox]').on('change', function (e) {&nbsp; &nbsp; if ($('input[type=checkbox]:checked').length > 3) {&nbsp; &nbsp; &nbsp; &nbsp; $(this).prop('checked', false);&nbsp; &nbsp; &nbsp; &nbsp; alert("allowed only 3");&nbsp; &nbsp; }});在JSFiddle中检查一下

小唯快跑啊

试试这个DEMO:&nbsp;$(document).ready(function () {&nbsp; &nbsp;$("input[name='vehicle']").change(function () {&nbsp; &nbsp; &nbsp; var maxAllowed = 3;&nbsp; &nbsp; &nbsp; var cnt = $("input[name='vehicle']:checked").length;&nbsp; &nbsp; &nbsp; if (cnt > maxAllowed)&nbsp;&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$(this).prop("checked", "");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;alert('Select maximum ' + maxAllowed + ' Levels!');&nbsp; &nbsp; &nbsp;}&nbsp; });});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JQuery