Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
90
rated 0 times [  95] [ 5]  / answers: 1 / hits: 146990  / 15 Years ago, thu, october 8, 2009, 12:00:00

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?


More From » html

 Answers
3

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 ===


[#98556] Thursday, October 1, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazlynnessencec

Total Points: 434
Total Questions: 113
Total Answers: 94

Location: Norway
Member since Mon, May 23, 2022
2 Years ago
;