我在 jquery 中编写了以下函数
<script>
function validateAppliesTo()
{
if ($("#collapseCat_row input:checkbox:checked").length > 0)
{
return true;
} else
{
swal({
title: "",
text: "Please select any course for which the fee should apply! "
});
return false;
}
if ($("#accordion_cat input:checkbox:checked").length > 0)
{
return true;
} else
{
swal({
title: "",
text: "Please select any category! "
});
return false;
}
return true;
}
</script>
上面的代码适用于#course_condition_row,但不适用于#accordion_cat。
在 html 中
<div class="panel panel-default">
<div class="panel-heading">
<h5 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion_cat" href="#collapseCat">Category</a>
</h5>
</div>
<div id="collapseCat" class="panel-collapse collapse in">
<div class="panel-body">
<input name="student_category[]" class="cls_categories" id="General" value="3" type="checkbox"> General<br>
<input name="student_category[]" class="cls_categories" id="Reserved" value="4" type="checkbox"> Reserved<br>
</div>
</div>
</div>
我想验证表单。如果在 Accordion 类别中没有选择任何复选框,那么它应该返回 false...
请帮助我!!!
最佳答案
一旦 validateAppliesTo() 函数到达返回
,该函数的其余部分将不会被执行。因此,只会处理第一个 if/else,而不会处理第二个。
在下面的代码中,我删除了 return
并更改了 if()
语句。
删除返回
删除返回
将确保所有代码都运行。
改变 if() 语句
如果没有选中任何复选框,.length
将返回 0,在 if()
语句中等于 true
。通过在语句前面添加 !
可以扭转这个结果。
简而言之:如果没有找到复选框,请输入此 if()
语句。
我还将 #accordion_cat
更改为 #collapseCat
,以便 JS 与提供的 HTML 相匹配。
结果
结果是,如果没有选中任何复选框,swal()
代码现在会被调用两次。
我不知道这个函数应该做什么,但请注意它被调用两次,并且第二次可能会覆盖第一次调用时的任何结果。
$(function() {
$( "#validate" ).click(function() {
validateAppliesTo()
});
function validateAppliesTo()
{
if (!$("#collapseCat_row input:checkbox:checked").length)
{
swal({
title: "",
text: "Please select any course for which the fee should apply! "
});
}
if (!$("#collapseCat input:checkbox:checked").length)
{
swal({
title: "",
text: "Please select any category! "
});
}
}
function swal(obj){
console.debug('do swal with', obj);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-default">
<div class="panel-heading">
<h5 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion_cat" href="#collapseCat">Category</a>
</h5>
</div>
<div id="collapseCat" class="panel-collapse collapse in">
<div class="panel-body">
<input name="student_category[]" class="cls_categories" id="General" value="3" type="checkbox"> General<br>
<input name="student_category[]" class="cls_categories" id="Reserved" value="4" type="checkbox"> Reserved<br>
</div>
</div>
</div>
<button id="validate">Validate</button>
关于javascript - 检查复选框是否被选中时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46425237/