I'm trying to validate a form using the validate plugin for jquery. I want to require that the user check at least one checkbox in a group in order for the form to be submitted. Here's my jquery code:
$().ready(function() { $("#subscribeForm").validate({ rules: { list: {required: "#list0:checked"} }, messages: { list: "Please select at least one newsletter"} }); });
and here's the html form:
<form action="" method="GET" id="subscribeForm"> <fieldset id="cbgroup"> <div><input name="list" id="list0" type="checkbox" value="newsletter0" >zero</div> <div><input name="list" id="list1" type="checkbox" value="newsletter1" >one</div> <div><input name="list" id="list2" type="checkbox" value="newsletter2" >two</div> </fieldset> <input name="submit" type="submit" value="submit">
The problem is that the form submits even if nothing is checked. How can I resolve this?
change(function() { $("#myform input:checkbox"). attr("checked", false); $(this). attr("checked", true); }); This should work for any number of checkboxes in the form.
Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.
$('#subscribeForm').validate( { rules: { list: { required: true, minlength: 1 } } });
I think this will make sure at least one is checked.
This script below should put you on the right track perhaps?
You can keep this html the same (though I changed the method to POST):
<form method="POST" id="subscribeForm"> <fieldset id="cbgroup"> <div><input name="list" id="list0" type="checkbox" value="newsletter0" >zero</div> <div><input name="list" id="list1" type="checkbox" value="newsletter1" >one</div> <div><input name="list" id="list2" type="checkbox" value="newsletter2" >two</div> </fieldset> <input name="submit" type="submit" value="submit"> </form>
and this javascript validates
function onSubmit() { var fields = $("input[name='list']").serializeArray(); if (fields.length === 0) { alert('nothing selected'); // cancel submit return false; } else { alert(fields.length + " items selected"); } } // register event on form, not submit button $('#subscribeForm').submit(onSubmit)
and you can find a working example of it here
UPDATE (Oct 2012)
Additionally it should be noted that the checkboxes must have a "name" property, or else they will not be added to the array. Only having "id" will not work.
UPDATE (May 2013)
Moved the submit registration to javascript and registered the submit onto the form (as it should have been originally)
UPDATE (June 2016)
Changes == to ===
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