jQuery Validation plugin: add/remove class to/from element's error container

£可爱£侵袭症+ 提交于 2019-12-18 04:36:08

问题


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>.

the HTML ...

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

... 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>

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 ?

Any help would be greatly appreciated !


Edited: Added more information.


回答1:


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 !




回答2:


errorElement: 'none' worked for me.



来源:https://stackoverflow.com/questions/2505053/jquery-validation-plugin-add-remove-class-to-from-elements-error-container

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