使用工具提示进行jquery验证

时间:2013-05-06 22:39:23

标签: jquery jquery-validate

是否可以将jquery validator与某种工具提示集成?

以下是我要做的事情: 我有一个联系表单,任何字段的焦点,我想要一个实时的工具提示出现,引导访问者进入键入的内容,一旦工具提示对字段值满意,它显示“已接受”。在此之前,它报告错误,例如“姓名必须至少为5个字符”或“您必须输入有效的电子邮件地址。”

然后在提交时,我想显示所有未被接受的工具提示。我也希望它们以与onfocus时相同的方式淡入和动画。 我也希望这些工具提示淡出,当我为其中一个字段聚焦时,我聚焦的字段无法通过fadeIn的动画运行,因为它已经显示。

有关如何轻松完成此任务的任何想法?

2 个答案:

答案 0 :(得分:1)

以下是您需要的所有内容,它也有动画>> FIDDLE Example

<强> HTML

<input type="text" id="txt1" />
<input type="text" id="txt2" />
<div id="tt"></div>

<强> CSS

 #tt{width:0px; height:0px; visibility':hidden; margin-left: -500px; background-color:red;}

<强>的jQuery

$('#txt1').focus(function(){
$('#tt').css({'width':'200px', 'height':'50px', 'visibility':'visible', 'background-color':'red'}).html('you clicked text field ONE').animate({'marginLeft':'10px'},1000)
});
$('#txt2').focus(function(){
    $('#tt').css({'width':'300px', 'height':'50px', 'visibility':'visible', 'background-color':'yellow'}).html('you clicked text field TWO').animate({'marginLeft':'150px'},1000)
});

答案 1 :(得分:1)

工作演示:http://jsfiddle.net/bvu5f/

这个答案使用了一个名为Tooltipster的jQuery插件以及jQuery Validate插件。

首先,在显示错误的所有特定form元素上初始化Tooltipster插件(with any options):

$(document).ready(function () {

    // initialize tooltipster on form input elements
    $('#myform input[type="text"]').tooltipster({ 
        trigger: 'custom', // default is 'hover' which is no good here
        onlyOne: false,    // allow multiple tips to be open at a time
        position: 'right'  // display the tips to the right of the element
    });

});

其次,使用Tooltipster's advanced optionssuccess: and errorPlacement: callback functions built into the Validate plugin自动显示和隐藏工具提示,如下所示:

$(document).ready(function () {

    // initialize validate plugin on the form
    $('#myform').validate({
        // any other options & rules,
        errorPlacement: function (error, element) {
            $(element).tooltipster('update', $(error).text());
            $(element).tooltipster('show');
        },
        success: function (label, element) {
            // $(element).tooltipster('hide'); // normal validate behavior
            $(element).tooltipster('update', 'accepted'); // as per OP
        }
    });

});

Code利用了2013年2月12日版本2.1中发布的新Tooltipster API功能