Reputation: 85
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
Upvotes: 1
Views: 25382
Reputation: 7663
$("#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
Upvotes: 8
Reputation: 34107
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;
});
});
Upvotes: 0
Reputation: 8476
try this
$('form').submit(function(e) {
if($("input:checked").length == 0){
alert('please checked atleast one');
}
});
Upvotes: 1
Reputation: 40673
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
}
Upvotes: 2