jQuery Validation插件:将类添加到元素的错误容器/从元素的错误容器中删除类 [英] jQuery Validation plugin: add/remove class to/from element's error container

查看:100
本文介绍了jQuery Validation插件:将类添加到元素的错误容器/从元素的错误容器中删除类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery Validation插件,并且编写了以下代码,如果无效,则将一个类添加到元素的(<input>)父对象(<label>),并插入实际的错误元素(<span>)之前.

I'm working with the jQuery Validation plugin and I wrote the following code which adds a class to the element's (<input>) parent (<label>) if not valid, as well as inserting the actual error element (<span>) before the <br>.

HTML ...

<label>
    text<br><input>
</label>

...和jQuery.

... and the jQuery.

$("#form_to_validate").validate({
    rules: {
    ...
    },
    errorElement: "span",
    errorPlacement: function(error, element) {
        element.parent().addClass('error');
        error.insertBefore(element.parent().children("br"));
    }
});

因此,如果表单元素未通过验证,它将变为:

So, if a form element doesn't validate, it turns into:

<label class="error">
    text<span>error text</span><br><input>
</label>

这很好用,但是,如果字段的内容被更正并变为有效,则该类显然不会从其父类中移除(实际上,error元素也不会删除,而是仅获得一个display: none; CSS属性) .如何检查元素是否有效并删除其父类?

This works great, however, if a field's content is corrected and becomes valid, the class obviously doesn't get removed from its parent (actually, neither does the error element, instead it just gets a display: none; CSS property). How can I check if an element becomes valid and remove its parent class if so ?

任何帮助将不胜感激!

添加了更多信息.

推荐答案

经过一番沉重的挖掘,我发现了答案在我的鼻子底下,但不幸的是,它隐藏了.该插件具有内置的突出显示功能(惊喜,惊喜).通常,它将突出显示/取消突出显示元素,但是可以轻松将其转换为在元素的父元素上工作:

After some more heavy digging I found the answer right under my nose, but unfortunately for me, well hidden. The plug-in has a built-in highlighting function (surprise, surprise). Normally it would highlight/unhighlight the element, but it can easily be converted to work on the element's parent:

$("#form_to_validate").validate({
    rules: {
    ...
    },
    errorElement: "span",
    errorPlacement: function(error, element) {
        error.insertBefore(element.parent().children("br"));
    },
    highlight: function(element) {
        $(element).parent().addClass("error");
    },
    unhighlight: function(element) {
        $(element).parent().removeClass("error");
    }
});

我希望这会对某人有所帮助!

I hope this will help someone !

这篇关于jQuery Validation插件:将类添加到元素的错误容器/从元素的错误容器中删除类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆