I currenlty have some javascript/jquery code that displays an error message if no boxes are checked. However when I check a box and submit the form the error message still displays.
any help would be great!
javascript code:
var hobbies = $('#hobbies').val();
if ($('#hobbies :checkbox:checked').length === 0){
$("#multichk").after('<span class="error">Please choose at least one.</span>');
hasError = true;
}
html code:
<input type='checkbox' id='hobbies' name='hobbies[0]' value='1'/><label for='hobbies0'>football</label><br />
<input type='checkbox' id='hobbies' name='hobbies[1]' value='2'/><label for='hobbies1'>soccer</label><br />
<input type='checkbox' id='hobbies' name='hobbies[2]' value='3'/><label for='hobbies2'>baseball</label><br />
<input type='checkbox' id='hobbies' name='hobbies[3]' value='4'/><label for='hobbies3'>tennis</label><br />
<input type='hidden' id='multichk' />
Thank you.
The way you have the checkboxes named and identified, they won’t be part of the same group, and they won’t be properly identified.
Each element on a page, when identified, must have a unique ID, and for a group of checkboxes, or radio buttons for that matter, to be validated and delivered as a group, each member of the group must have the same name.
Given these rules, it should come as no surprised that the
forattribute of a label tag references an element’sidattribute, rather than itsnameattribute.Now, I’m guessing that you’re using PHP for your server-side language (based on the brackets in the checkbox names), in which case the checkboxes should be declared like so:
[Note: labels only moved to next line to remove horizontal scroll in code box]
With the HTML straightened out, the jQuery would look something like this:
Reference for selector format
If that selector still gives you trouble, then you may need to prefix the square brackets with double backslashes like this:
Reference for double backslashes
Hope this helps