views:

335

answers:

4

All,

I have the following HTML form and it can have many checkboxes. When the submit button is clicked, I want the user to get a javascript alert to check atleast one checkbox if none are checked. Is there an easy way to do this using Jquery?

<form name = "frmTest" id="frmTest">
<input type="checkbox" value="true" checked="true" name="chk[120]">
<input type="checkbox" value="true" checked="true" name="chk[128]">
<input type="checkbox" name="chk[130]">
<input type="checkbox" name="chk[143]">
<input type="submit" name="btnsubmit" value="Submit">
</form>

Thanks

+1  A: 
$('#frmTest input:checked').length > 0
Matthew Flaschen
$('#frmTest:checkbox').length > 0 would be better to check among a certain number of checkboxes.
Kasturi
Why would radio-buttons be better? If the OP wants *at least* one option selected radio-buttons would limit him to one *at most*.
David Thomas
@David, I've removed that suggestion.
Matthew Flaschen
:) and +1 (padding)
David Thomas
+1  A: 
$("#frmTest").submit(function(){
    var checked = $("#frmText input:checked").length > 0;
    if (!checked){
        alert("Please check at least one checkbox");
        return false;
    }
});
Jon
+4  A: 
if(jQuery('#frmTest input[type=checkbox]:checked').length) { … }
David Dorward
A: 
$('#frmTest').submit(function(){
    if(!$('#frmTest input[type="checkbox"]').is(':checked')){
      alert("Please check at least one.");
      return false;
    }
});

is(':checked') will return true if at least one or more of the checkboxes are checked.

namklabs