I am having trouble using jQuery validator.addMethod to validate check boxes based on class names as opposed to names.
Take a look at this and tell me why the script doesn’t work when placed within script tags inside the html.
The code is here: http://jsbin.com/ecozih/2
If you move the script over to the JavaScript window on JS bin it works.
If there is a easier way to do this, please let me know. An example would be greatly appreciated.
<html>
<head>
<script src="hxxp://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="hxxp://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
</head>
<body>
<script>
$.validator.addMethod('interests', function (value) {
return $('.interests:checked').size() > 0; }, 'Pick one or more');
var checkboxes = $('.interests');
var checkbox_names = $.map(checkboxes, function(e,i) { return $(e).attr("name")}).join(" ");
$("#subscribeForm").validate({
groups: { checks: checkbox_names },
errorPlacement: function(error, element) {
if (element.attr("type") == "checkbox")
error.insertAfter(checkboxes.last());
else
error.insertAfter(element);
}
});
</script>
<form name="subscribeForm" id="subscribeForm" method="post">
<input type="checkbox" class="interests" value="1" name="group[1357][1]" ><label>Bananas</label>
<input type="checkbox" class="interests" value="2" name="group[1357][2]"><label>Oranges</label>
<input type="checkbox" class="interests" value="4" name="group[1357][4]"><label>Apples</label><br />
<label for="checks" generated="true" class="error" style=""></label><br />
<input type="submit" />
</form>
</body>
Thank you
You forgot to wrap your jQuery code within a
document.ready. In other words, your jQuery is trying to select elements before the elements have even been constructed. Thedocument.readyfixes this. Since theformdoes not yet exist when the code is called, thedocument.readyonly fires off when the HTML DOM is ready.jsFiddle Demo: http://jsfiddle.net/TCHYJ/
and your jsBin: http://jsbin.com/ecozih/4/edit
Quote: “If you move the script over to the JavaScript window on JS bin it works.”
That’s because, code inside the JavaScript panes of jsBin and jsFiddle wait for the DOM to load before being fired whether you use the
document.readyor not.http://jsfiddle.net/TCHYJ/1/
http://jsbin.com/ecozih/6/edit