2016-11-01 67 views
0

我有以下html和jQuery代码段来验证至少一个复选框。我是新的jQuery,所以我无法验证这两个复选框。请帮帮我。谢谢JQuery复选框验证一个

<div class="row"> 
    <div class="form-horizontal"> 
     <label class="col-sm-5 control-label input-sm">Payement Type</label> 
     <div class="col-sm-5"> 
      <span id="errfnBC9" style="color:red;font-size:8pt"></span> 
      <input type="checkbox" name="cashactive" id="activecash" value="Cash" checked style="font-weight: bold;font-size: 11px;">&nbsp;&nbsp;Cash 
        <input type="checkbox" name="creditactive" id="activecredits" value="Credit" style="font-weight: bold;font-size: 11px;">&nbsp;&nbsp;Credit<br> 
     </div> 
    </div> 
</div> 

    if ($('#activecash').find('input[type=checkbox]:checked').length == 0) { 
     document.getElementById('errfnBC9').style.display = "block"; 
     document.getElementById('errfnBC9').innerHTML = "**Please select at least one checkbox"; 
     return false; 
    } 
+0

如果你正在写的东西上使用一个真正的网站,你可以利用我建立的形成验证库 - http://www.github.com/ozzyogkush/formation - 它各种元素类型,包括收音机/复选框 – Derek

+0

也这个特殊的用例将更适合'收音机'按钮,因为用户只会选择一个选项,不会超过一个 – Derek

回答

0

只能使用JavaScript或jQuery的。适用与onchange事件会验证每次检查的时间。

$(document).ready(function(){ 
 
$('input[type=checkbox]').on('change',function(){ 
 
    if ($('input[type=checkbox]:checked').length == 0) { 
 
    $('#errfnBC9').html("**Please select atleast one checkbox"); 
 
    } 
 
    else{ 
 
     
 
     $('#errfnBC9').html(""); 
 
    
 
    } 
 
    }); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="row"> 
 
         <div class="form-horizontal"> 
 
          <label class="col-sm-5 control-label input-sm">Payement Type</label> 
 
          <div class="col-sm-5"> 
 
           <span id="errfnBC9" style="color:red;font-size:8pt"></span><br> 
 
           <input type="checkbox" name="cashactive" id="activecash" value="Cash" checked style="font-weight: bold;font-size: 11px;">&nbsp;&nbsp;Cash 
 
           <input type="checkbox" name="creditactive" id="activecredits" value="Credit" style="font-weight: bold;font-size: 11px;">&nbsp;&nbsp;Credit<br> 
 

 
          </div> 
 
         </div> 
 
        </div>

0

您必须添加一个事件监听器时看到的复选框的状态正在改变:

$(".validate").on("change", function(e) { 
 
    if($("input.validate:checked").length == 0) { 
 
     $("#error").html("You must select one."); 
 
    } else { 
 
     $("#error").html(""); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<input type="checkbox" id="cash" class="validate" checked /><label for="cash">Cash</label> 
 
<input type="checkbox" id="credit" class="validate" /><label for="credit">Credit</label> 
 

 
<p id="error"></p>