How to display unique success messages on jquery form validation

扶醉桌前 提交于 2019-12-19 10:26:25

问题


hope you can help me on this one, I'm currently using this:

jQuery plugin:validation (Homepage)

I've been reading related questions here, but this one is the closest get. httx://stackoverflow.com/questions/1863448/jquery-validation-on-success

from the plugin's documentation httx://docs.jquery.com/Plugins/Validation/validate#toption

success String, Callback
If specified, the error label is displayed to show a valid element. If a String is given, its added as a class to the label. If a Function is given, its called with the label (as a jQuery object) as its only argument. That can be used to add a text like "ok!".

Currently I'm only object given to me is the label, and I can only add text to it. Now what I want is to have unique success message.

For example: username field will have a success message: 'username okay!'
email = 'email seems right'

something along those lines, instead of displaying just one generic success message on all the fields.

Edit:

I only tried this so far:

success: function(label) {
    label.text("Ok!").removeClass("error").addClass("success");
    },

EDIT just want to edit, what I wanted is a way to access the input element and probably access its attribute, to use it to display on the label.text. Something like label.text(element.attr("title"); for example.


回答1:


The simplest i can think of is as such:

jQuery(function($) {
    $('form').validate({
        success: function(label) {
            var name = label.attr('for');
            label.text(name+ ' is ok!');
        }
    });
});

<form action="" method="post">
    <input name="username" class="required" type="text" />
    <input type="submit" />
</form>

If you want more unique messages, maybe you can store your message somewhere (an additional hidden field, or additional DOM, or use metadata). Make sure it's in a consistent position (so you can traversing it is the same for all fields) and update the label message accordingly?




回答2:


For whats it worth here is the code I used to display a unique random success message.

success: function(label) {
        var messages = new Array(
            "Looks good!",
            "You got it!",
            "Ok!"
        );

        var num = Math.floor(Math.random()*3); 

        label.text(messages[num]).addClass("success");
    }


来源:https://stackoverflow.com/questions/2831680/how-to-display-unique-success-messages-on-jquery-form-validation

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