2016-11-01 65 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>