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>
change(function() { $("#myform input:checkbox"). attr("checked", false); $(this). attr("checked", true); }); This should work for any number of checkboxes in the form.
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[]"]').
if(jQuery('#frmTest input[type=checkbox]:checked').length) { … }
$('#frmTest input:checked').length > 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With