jQuery验证:向父div添加错误或验证类 [英] jQuery Validate: add error or validate class to parent div

查看:91
本文介绍了jQuery验证:向父div添加错误或验证类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Twitter的Bootstrap作为我正在从事的项目的框架.我正在尝试使用jQuery Validate插件来验证简单的联系表单,但这会引起一些麻烦.

I am using Twitter's Bootstrap as my framework for a project I am working on. I am attempting to validate a simple contact form using the jQuery Validate plugin but it's causing some headaches.

我想在每个表单输入的父div 中添加一个 Error Valid 类.这是我的表单代码:

I'm looking to add an Error or Valid class to the parent div of each form's input. Here's my form code:

 <form id="msg-form" class="">
    <fieldset>
        <div class="input-prepend control-group pull-left">
            <span class="add-on">@</span>
            <input class="span3 required email" id="inputEmail" name="msg-email" type="text" placeholder="example@example.com">
        </div>
        <div class="input-prepend control-group pull-left">
            <span class="add-on"><i class="icon-user"></i></span>
            <input class="span3 required" id="inputName" name="msg-name" type="text" placeholder="Joe Bloggs">
        </div>
        <div class="input-prepend control-group">
            <span class="add-on" style="height: 53px;"><i class="icon-pencil"></i></span>
            <textarea class="span3 required" id="textarea" name="msg-comments" rows="2" style="height: 53px" placeholder="Just say hi, or tell us how we can help"></textarea>
        </div>
        <button type="submit" class="btn pull-right">Submit<i class="icon-chevron-right"></i></button>
    </fieldset>
</form> 

如您所见,我的 div.control-group 是我要添加该类的div.我尝试使用突出显示(如建议在此处,但这根本行不通)& errorPlacement (如下所示),但我没有正确执行.

As you can see my div.control-group is the div I want to add the class to. I have attempted to use the highlight (as suggested here, but this simply didn't work) & errorPlacement (see below) but I'm not doing it correctly.

理想情况下,我希望在键盘上添加/删除该类,以使其保持插件提供的强大功能.这个简单的代码可以运行,但不会删除类&仅适用于以下形式的提交:

Ideally I want the class to be added/removed on keyup so it keeps the great functionality that the plugin offers. This simple code works, but it does not remove the class & only works on submission of the form:

$("#msg-form").validate({
    errorPlacement: function(error, element) {
        $(element).parent('div').addClass('error');
    }
});

谁能建议我应该使用什么选项来实现这一目标?

Can anyone suggest what option I should be using to achieve this?!

预先感谢-我可以在必要时提供其他详细信息!

Thanks in advance - I can provide any additional details in necessary!

推荐答案

尝试使用highlightunhighlight函数:

$("#msg-form").validate({
    highlight: function(element) {
        $(element).parent('div').addClass('error');
    },
    unhighlight: function(element) {
        $(element).parent('div').removeClass('error');
    }
});

这篇关于jQuery验证:向父div添加错误或验证类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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