简体   繁体   中英

check at least one checkbox validation in jquery

I have some checkboxes, something like this:

<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>

I would like to validate that atleast one checkbox at a time. plz help me. thanks in advance

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

Update:

i saw your code and seems like you are using jquery validation plugin in that case this post will help you

and try giving your checkbox same name which exist in a group

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

I'd wrap them all in a container with a div just for easier selecting, and then you can use:

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

try this

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

See this demo: http://jsfiddle.net/RGUTv/ OR your specific case demo here: http://jsfiddle.net/J98Ua/

My old response here: validation for at least one checkbox

hope rest fits the needs! :)

code

$(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;
    });
});​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM