多个复选框>至少应显示一条强制性的其他错误消息

时间:2017-04-10 10:13:05

标签: javascript jquery html forms

如何确保访问者在提交表单之前勾选/选择至少一个选项?

这是我的代码的摘录:

<div class="col-md-6" id="ajax_succs">
<div class="check_parent">
<input type="checkbox" name="sub_sub_cat_select[]" class="default_checkbox" value="351">Option 1</div>
<div class="check_parent">
<input type="checkbox" name="sub_sub_cat_select[]" class="default_checkbox" value="353">Option 2</div>
<div class="check_parent">
<input type="checkbox" name="sub_sub_cat_select[]" class="default_checkbox" value="354">Option 3</div>
<div class="check_parent">
<input type="checkbox" name="sub_sub_cat_select[]" class="default_checkbox" value="355">Option 4</div>
...

1 个答案:

答案 0 :(得分:3)

找到length输入的checked。请尝试以下方法:

&#13;
&#13;
$('#btnSubmit').click(function(){
    var chkSelected = $('input:checked').length;
    if(chkSelected <= 0){
        console.log('No checkbox selected');
    }
    else{
        console.log('Checkbox selected');
    }
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="check_parent">
<input type="checkbox" name="sub_sub_cat_select[]" class="default_checkbox" value="351">Option 1</div>
<div class="check_parent">
<input type="checkbox" name="sub_sub_cat_select[]" class="default_checkbox" value="353">Option 2</div>
<div class="check_parent">
<input type="checkbox" name="sub_sub_cat_select[]" class="default_checkbox" value="354">Option 3</div>
<div class="check_parent">
<input type="checkbox" name="sub_sub_cat_select[]" class="default_checkbox" value="355">Option 4</div><br>
<input type="submit" id="btnSubmit" name="" value="Submit">
&#13;
&#13;
&#13;