Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use jQuery to check whether at least one checkbox is checked?

I have the following HTML form which can have many checkboxes. When the submit button is clicked, I want the user to get a javascript alert to check at least 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> 
like image 534
Jake Avatar asked Apr 21 '10 15:04

Jake


People also ask

How do you make sure only one checkbox is checked?

change(function() { $("#myform input:checkbox"). attr("checked", false); $(this). attr("checked", true); }); This should work for any number of checkboxes in the form.

How can I check if multiple checkboxes are checked in jQuery?

Since you're providing the same name attribute to all the checkboxes (from your PHP loop), you can use the selector input[name="city[]"] to target and find them all. But to find out how many specifically are checked, you can add the :checked selector. An alternative to this is using $('input[name="city[]"]').


2 Answers

if(jQuery('#frmTest input[type=checkbox]:checked').length) { … } 
like image 144
Quentin Avatar answered Oct 04 '22 03:10

Quentin


$('#frmTest input:checked').length > 0 
like image 41
Matthew Flaschen Avatar answered Oct 04 '22 05:10

Matthew Flaschen