I'm using the jQuery validate plugin, and would like to return a random value on success.
我正在使用jQuery validate插件,并希望在成功时返回一个随机值。
Right now I'm trying to use:
现在我正在尝试使用:
var success_message = new Array ();
success_message[0] = "Good!";
success_message[1] = "Ok!";
success_message[2] = "Great!";
success_message[3] = "Perfect!";
success_message[4] = "Nice!";
success_message[5] = "Awesome";
var i = Math.floor(5*Math.random())
Then where I need to output the value I use:
然后我需要输出我使用的值:
$(document).ready(function(){
var validator = $(".contactform").validate({
success: function(label) {
label.addClass("valid").text(success_message[i])
}
}); //end form validate code
});
This selects a random value but uses the same value for each success message instead of selecting a different one for each field.
这会选择一个随机值,但对每个成功消息使用相同的值,而不是为每个字段选择不同的值。
3 个解决方案
#1
79
You can store the messages
array and calculate the message to show as you go, like this:
您可以存储messages数组并计算要显示的消息,如下所示:
var messages = ["Good!", "Great!", "Awesome!", "Super!", "Nice!"];
function getMessage() {
return messages[Math.floor(Math.random() * messages.length)];
}
Give it a try here, then just call getMessage
in your .text()
call, like this:
在这里尝试一下,然后在.text()调用中调用getMessage,如下所示:
label.addClass("valid").text(getMessage());
#2
4
We can add Method to Array.
我们可以添加Method to Array。
Array.prototype.getRandomVal = function(){
return this[Math.floor(Math.random()*this.length)];
};
messages.getRandomVal();
#3
3
function sucess() {
message = ["Good!","Awesome!","Super!","Nice!","Great!"];
return message[Math.floor(Math.random() * message.length)];
}
$(document).ready(function(){
var validator = $(".contactform").validate({ ...
success: function(label) {
label.addClass("valid").text(success());
}
}); //end form validate code
});
#1
79
You can store the messages
array and calculate the message to show as you go, like this:
您可以存储messages数组并计算要显示的消息,如下所示:
var messages = ["Good!", "Great!", "Awesome!", "Super!", "Nice!"];
function getMessage() {
return messages[Math.floor(Math.random() * messages.length)];
}
Give it a try here, then just call getMessage
in your .text()
call, like this:
在这里尝试一下,然后在.text()调用中调用getMessage,如下所示:
label.addClass("valid").text(getMessage());
#2
4
We can add Method to Array.
我们可以添加Method to Array。
Array.prototype.getRandomVal = function(){
return this[Math.floor(Math.random()*this.length)];
};
messages.getRandomVal();
#3
3
function sucess() {
message = ["Good!","Awesome!","Super!","Nice!","Great!"];
return message[Math.floor(Math.random() * message.length)];
}
$(document).ready(function(){
var validator = $(".contactform").validate({ ...
success: function(label) {
label.addClass("valid").text(success());
}
}); //end form validate code
});