我有以下html和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;"> Cash
<input type="checkbox" name="creditactive" id="activecredits" value="Credit" style="font-weight: bold;font-size: 11px;"> 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 :(得分:0)
您必须添加一个事件侦听器,以查看复选框的状态何时发生变化:
$(".validate").on("change", function(e) {
if($("input.validate:checked").length == 0) {
$("#error").html("You must select one.");
} else {
$("#error").html("");
}
});
&#13;
<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>
&#13;
答案 1 :(得分: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( "");
}
});
});
&#13;
<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;"> Cash
<input type="checkbox" name="creditactive" id="activecredits" value="Credit" style="font-weight: bold;font-size: 11px;"> Credit<br>
</div>
</div>
</div>
&#13;