在jquery中检查至少一个复选框验证

时间:2012-10-27 06:12:07

标签: jquery forms checkbox

我有一些复选框,如下所示:

<form name="submit-form" name="submit-form">
<label>property1</label>
<input type="checkbox" name="property1"><br>
<label>property2</label>
<input type="checkbox" name="property2"><br>
<label>property3</label>
<input type="checkbox" name="property3"><br>
<label>property4</label>
<input type="checkbox" name="property4"><br>
<label>property5</label>
<input type="checkbox" name="property5"><br>
<label>property6</label>
<input type="checkbox" name="property6"><br>
<input type="submit">
</form>

我想一次验证至少一个复选框。请帮助我。提前谢谢

4 个答案:

答案 0 :(得分:7)

$("#YourbuttonId").click(function(){
    if($('#YourTableId').find('input[type=checkbox]:checked').length == 0)
    {
        alert('Please select atleast one checkbox');
    }
});

<强>更新

我看到你的代码,看起来你正在使用jquery验证插件,在这种情况下这篇文章会帮助你

并尝试为您的复选框指定一个存在于组中的名称

http://forum.jquery.com/topic/check-that-at-least-1-checkbox-is-checked-using-jquery-validate-plugin

答案 1 :(得分:1)

我将它们全部包装在带有div的容器中以便于选择,然后您可以使用:

if($('#wrapperID input:checked').length > 0) {
    'at least one is checked
}

答案 2 :(得分:0)

试试这个

$('form').submit(function(e) {
    if($("input:checked").length == 0){
    alert('please checked atleast one');
    }
});​

答案 3 :(得分:0)

在此处观看此演示:http://jsfiddle.net/RGUTv/ 您的具体案例演示:http://jsfiddle.net/J98Ua/

我在旧的回复:validation for at least one checkbox

希望休息符合需求! :)

<强>码

$(document).ready(function() {
    $('#my-form').submit(function() {
        amIChecked = false;
        $('input[type="checkbox"]').each(function() {
            if (this.checked) {
                amIChecked = true;
            }
        });
        if (amIChecked) {
            alert('atleast one box is checked');
        }
        else {
            alert('please check one checkbox!');
        }
        return false;
    });
});​
相关问题