如何在 Tooltipster 工具提示中显示来自 jQuery Validate 插件的消息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14741688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:52:51  来源:igfitidea点击:

How to display messages from jQuery Validate plugin inside of Tooltipster tooltips?

jqueryjquery-validatetooltiptooltipster

提问by Sparky

I'd like to use the Tooltipster pluginto display form errors generated by the jQuery Validate plugin.

我想使用Tooltipster 插件来显示由jQuery Validate 插件生成的表单错误。

jQuery for Validate plugin:

jQuery 验证插件

$(document).ready(function () {

    $('#myform').validate({ // initialize jQuery Validate
        // other options,
        rules: {
            field1: {
                required: true,
                email: true
            },
            field2: {
                required: true,
                minlength: 5
            }
        }
    });

});

jQuery for Tooltipster plugin:

jQuery for Tooltipster 插件

$(document).ready(function () {

    $('.tooltip').tooltipster({ /* options */ });  // initialize tooltipster

});

HTML:

HTML:

<form id="myform">
    <input type="text" name="field1" />
    <input type="text" name="field2" />
    <br/>
    <input type="submit" />
</form>

How would I integrate the usage of these two jQuery plugins so that validation errors appear inside the tooltips?

我将如何集成这两个 jQuery 插件的使用,以便在工具提示中显示验证错误?

回答by Sparky

Solutions for Tooltipster versions 2.1, 3.0, & 4.0 are included in this answer.

此答案中包含 Tooltipster 版本 2.1、3.0 和 4.0 的解决方案。

NOTEthat .tooltipster()is only attached to a type="text"inputelement in my examples below. If your formcontains other kinds of data input elements such as type="radio", type="date", textarea, select, etc., then you mustadjust your selector accordingly or create additional instances of .tooltipster()for these other elements. Otherwise, everything will fail with errors.

请注意,在我下面的示例中,.tooltipster()它仅附加到一个type="text"input元素。如果form包含其他类型的数据输入等元件type="radio"type="date"textareaselect,等等,那么你就必须相应地调整你的选择或创建的其他实例.tooltipster(),这些其他元素。否则,一切都会因错误而失败。



Tooltipster v2.1

工具提示 v2.1

First, initialize the Tooltipster plugin (with any options) on allspecific formelements that will display errors:

首先,在将显示错误的所有特定元素上初始化 Tooltipster 插件(带有任何选项):form

$(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
    });

});

Second, use Tooltipster's advanced optionsalong with the success:and errorPlacement:callback functions built into the Validate pluginto automatically show and hide the tooltips as follows:

其次,使用Tooltipster 的高级选项以及内置于 Validate 插件中success:errorPlacement:回调函数来自动显示和隐藏工具提示,如下所示:

$(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');
        }
    });

});

Working Demo: http://jsfiddle.net/2DUX2

工作演示:http: //jsfiddle.net/2DUX2

EDIT: Updated code to take advantage of the new Tooltipster API features released in version 2.1 on 2/12/13

编辑:更新代码以利用 2/12/13 版本 2.1 中发布的新 Tooltipster API 功能





UPDATE for Tooltipster v3.0

Tooltipster v3.0 更新

Tooltipster 3.0 is out and as such doesn't work the same as illustrated above. The following code provides an updated example. This version has the added benefit of not calling Tooltipster on every keystroke when the message has not yet changed.

Tooltipster 3.0 已发布,因此与上图所示的工作方式不同。以下代码提供了一个更新的示例。此版本的另一个好处是,当消息尚未更改时,不会在每次击键时调用 Tooltipster。

(Don't forget that you still need to attach .tooltipster()to your relevant inputelements as illustrated above.)

不要忘记你仍然需要附加.tooltipster()到你的相关input元素,如上图所示。

$(document).ready(function () {

    // initialize validate plugin on the form
    $('#myform').validate({
        // any other options & rules,
        errorPlacement: function (error, element) {
            var lastError = $(element).data('lastError'),
                newError = $(error).text();

            $(element).data('lastError', newError);

            if(newError !== '' && newError !== lastError){
                $(element).tooltipster('content', newError);
                $(element).tooltipster('show');
            }
        },
        success: function (label, element) {
            $(element).tooltipster('hide');
        }
    });

});

DEMO using Tooltipster v3.0: jsfiddle.net/2DUX2/3/

使用 Tooltipster v3.0 的演示:jsfiddle.net/2DUX2/3/





UPDATE for Tooltipster v4.0

Tooltipster v4.0 更新

Note that the onlyOneoption has been removed from the 4.0 version of the Tooltipster plugin.

请注意,该onlyOne选项已从 Tooltipster 插件的 4.0 版本中删除。

I also replaced the successcallback with unhighlight. On "optional" fields, the error message was never removed when the field was subsequently blanked out... this is because the successfunction does not fire under these circumstances. This issue is not isolated to Tooltipster version 4, however the following code solves it moving forward.

我也successunhighlight. 在“可选”字段上,当该字段随后被清空时,错误消息从未被删除......这是因为success在这些情况下该函数不会触发。此问题并非孤立于 Tooltipster 版本 4,但以下代码解决了它的问题。

// initialize Tooltipster on text input elements
$('input[type="text"]').tooltipster({ //find more options on the tooltipster page
    trigger: 'custom', // default is 'hover' which is no good here
    position: 'top',
    animation: 'grow'
});

// initialize jQuery Validate
$("#myform").validate({
    errorPlacement: function (error, element) {
        var ele = $(element),
            err = $(error),
            msg = err.text();
        if (msg != null && msg !== '') {
            ele.tooltipster('content', msg);
            ele.tooltipster('open');
        }
    },
    unhighlight: function(element, errorClass, validClass) {
        $(element).removeClass(errorClass).addClass(validClass).tooltipster('close');
    },
    rules: {
        ....

DEMO using Tooltipster v4.0: https://jsfiddle.net/h5grrrr9/

使用 Tooltipster v4.0 的演示:https: //jsfiddle.net/h5grrrr9/

回答by Mgamerz

Sparky's answer has been a staple on my site's validation, but upgrading to Tooltipster 4 required some changes. Here's how I got mine working, and with a few improvements.

Sparky 的回答一直是我网站验证的主要内容,但升级到 Tooltipster 4 需要一些更改。这是我如何让我的工作,并有一些改进。

On your pages, include the tooltipster css and a theme css in the head section (and any theme css that you subclass their themes with as described on its page).

在您的页面上,在 head 部分包含 tooltipster css 和主题 css(以及您在其页面上描述的子类化其主题的任何主题 css)。

<link rel="stylesheet" type="text/css" href="/styles/tooltipster.bundle.css">
<link rel="stylesheet" type="text/css" href="/styles/tooltipster/sideTip/themes/tooltipster-sideTip-light.min.css">

Additionally, you need to include tooltipster's javascript file. You'll also need the jquery-validation javascript.

此外,您需要包含 tooltipster 的 javascript 文件。您还需要 jquery-validation javascript。

<script src="/js/tooltipster.bundle.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script>

Now, in either another javascript file or in some script tags, you'll need to put your validation code as well as your tooltipster code. Here's one from a webpage I have, the changes from Sparky's answer are at the top.

现在,在另一个 javascript 文件或某些脚本标签中,您需要放置验证代码以及工具提示代码。这是我拥有的网页中的一个,Sparky 的答案中的更改位于顶部。

$(document).ready(function(){

    $('#form input[type="text"]').tooltipster({ //find more options on the tooltipster page
        trigger: 'custom', // default is 'hover' which is no good here
        onlyOne: false,    // allow multiple tips to be open at a time
        position: 'top',
        animation: 'grow', 
        theme: ['tooltipster-light'] //put your themes here
    });

    //form validation initialization
    $("#form").validate({
        errorPlacement: function (error, element) {
            if (error[0].innerHTML != null && error[0].innerHTML !== "") {
                $(element).tooltipster('content', $(error).text());
                $(element).tooltipster('open'); //open only if the error message is not blank. By default jquery-validate will return a label with no actual text in it so we have to check the innerHTML.
            }
        },
        success: function (label, element) {
            var obj = $(element);
            if (obj.hasClass('tooltipstered') && obj.hasClass('error')) {
                $(element).tooltipster('close'); //hide no longer works in v4, must use close
            }   
        },
        rules: {
            // your rules
            ......
        }
    });

});

Now when you type something into a field that violates one of the listed rules, a popup comes up above the box saying what jquery-validate says is wrong. It also won't open a message if there is nothing in it to show the user (which would lead to it opening a blank tooltip and then immediately closing, which looks weird).

现在,当您在违反所列规则之一的字段中键入内容时,框上方会弹出一个弹出窗口,说明 jquery-validate 所说的内容是错误的。如果其中没有任何内容向用户显示,它也不会打开消息(这将导致它打开一个空白的工具提示然后立即关闭,这看起来很奇怪)。