【问题标题】:Restricting the number of checkboxes that can be selected限制可以选择的复选框数量
【发布时间】:2015-11-24 12:58:54
【问题描述】:

我正在尝试将可以选择的复选框数量限制为 3。下面的代码有效,但我想将其限制为包含复选框的 div 类 pricing-levels-3。

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>

jQuery

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

Fiddle:

【问题讨论】:

    标签: javascript jquery html checkbox


    【解决方案1】:

    试试这个Fiddle

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

    【讨论】:

      【解决方案2】:

      你应该阅读Selectors

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-20
        • 2013-04-26
        • 1970-01-01
        • 2023-03-26
        • 2023-04-01
        • 1970-01-01
        • 2011-02-27
        相关资源
        最近更新 更多