Using jQuery Validate's invalidHandler event

孤街浪徒 提交于 2019-12-23 05:58:20

问题


I need to add a class to div that is wrapped around the select element upon validation.

$("#Form").validate({
    invalidHandler: function (form, validator) {
        $("[id$='_DropDownList']").each(function () {
            // How do I figure out if $(this) is valid or invalid?
            // Add the class below if invalid.
            $(this).parent().addClass("error");
        });
    }
});

回答1:


You can use the .valid() method, like this:

$("#Form").validate({
    invalidHandler: function (form, validator) {
        $("[id$='_DropDownList']").each(function () {
            if(!$(this).valid())
              $(this).parent().addClass("error");
        });
    }
});

However, the highlight and unhightlight options are specifically for this:

$("#Form").validate({
  highlight: function(element, errorClass, validClass) {
    $(element).parent().removeClass(validClass).addClass(errorClass);
  },
  unhighlight: function(element, errorClass, validClass) {
    $(element).parent().removeClass(errorClass).addClass(validClass);
  }
});



回答2:


It looks like this code is correct:

$(this).parent().addClass("error");

Maybe your issue is with the code surrounding it... Try moving your addClass line outside the function it is in to see if it work there.




回答3:


invalidHandler is only called when the form is submitted and not valid. I believe adding your code under that function alone is enough.



来源:https://stackoverflow.com/questions/4616947/using-jquery-validates-invalidhandler-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!