带有警告弹出窗口的jQuery Validate插件 - 仍然出现 - 用户无法在选择框中选择正确的值

Jan*_*iak 5 jquery alert jquery-validate

我正在使用以下代码:

$().ready(function() {
    $('#state_form').validate({
        rules: {
            state: "required"
        },
        messages: {
            state: 
            {
                required: "The State is required!"
            }
        },          
        errorPlacement: function(error, element) {
            alert(error.html());
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

但如果用户提交表单,则会出现弹出错误.这是对的.然后,如果用户单击选择框"状态",则仍会显示带有错误的弹出窗口(无法选择正确的值).真实的例子可以在janzitniak.info/temp/test.php上找到

这是不可接受的.我怎么能解决这个问题?

JQuery表单验证中描述的解决方案带有警告弹出窗口 - 警报仍然显示有效提交没有帮助我,也许我没有正确理解.

Spa*_*rky 9

使用该onclick: false选项可防止在选择状态之前触发错误.此外,您只需要使用.text()而不是.html()因为alert()无论如何都不需要使用HTML.

$(document).ready(function () {
    $('#state_form').validate({
        onclick: false, // <-- add this option
        rules: {
            state: "required"
        },
        messages: {
            state: {
                required: "The State is required!"
            }
        },
        errorPlacement: function (error, element) {
            alert(error.text());
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

演示:http: //jsfiddle.net/U6N3R/

注意:不要在Safari中使用此代码,否则您将陷入无限循环.似乎alert()在Safari中errorPlacement点击"确定"按钮后第二次激活回调函数.


为了获得更现代的用户体验,我建议使用jQuery模式或工具提示插件.

请参阅此答案作为示例:https: //stackoverflow.com/a/14741689/594235