开发者

Javascript error with jQuery plugins when element not found

I'm using the jQuery Validation plugin with Wordpress to validate my contact page. I am noticing that on the contact page where there is a form, there are no Javascript errors in the 2 browsers I tested (IE7 and Firefox 4 with Firebug). On a different page where the script is loaded but there are no forms, Firebug reports:

jQuery("form").validate is not a function

IE7 says the page contains errors, too.

This is all I have so far:

jQuery(document).ready(function () {
    jQuery("form").validate({
        rules: {
            contactName: "required",
            email: {
                required: true,
                email: true
            },
            message: "required"
        },
        messages: {
            name: "A valid name is required.",
            email: "A valid email address is required.",
            message: "A message is required."
        },
        errorPlacement: function(error, element) {
            error.insertAfter( element.siblings("label") );
        }
 开发者_如何学编程   });
});

I'm trying to pack all the jQuery plugins together on one file instead of separating them and loading them individually. Why is it causing the error? I even tried replacing "form" with "#contact".


You can change the validation to first check for the existence of the element. Something like:

var $form = jQuery("form");
if ($form.length) {
  $form.validate({
    // your code
  });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜