jQuery Validate:使用选择选项更改所需的消息 [英] jQuery Validate: Change required message using select option
问题描述
当用户更改选择选项输入时,我一直在尝试动态更改表单所需规则的消息.我似乎无法正常工作.更改选择后,消息将永远不会改变.
I've been trying to change the message of the required rule for my form dynamically when the user changes the select option input. I can't seem to get anything to work properly. The message will never change after the selection is changed.
我尝试将change函数用于选择输入,如下所示:
I try my methods using the change function for the select input like so:
$('#selector').change(function(){
Method X;
}
我尝试过的方法:
-
$.validator.messages.required = "New Message";
$('#inputx').rules("remove", "required");
$('#inputx').rules("add", { messages: {required: "New Message"}});
我还尝试了消息的depends函数,但这根本不起作用:
I have also tried a depends function for the message, but that doesn't work at all:
required: {
depends: function(element){
if($('#selector option:selected').text() == 'Option1'){
return "Message 1";
} else{
return "Message 2";
}
return;
}
}
即使取消了#inputx元素的聚焦,错误消息也不会更改
The error message does not change even after unfocusing the #inputx element
我在onChange内执行了不正确的条件语句.现在一切正常!
I did an incorrect conditional statement inside my onChange. Everything works perfectly now!
推荐答案
.rules('add')
方法对我来说很好...
The .rules('add')
method is working fine for me...
$(document).ready(function () {
$('#myform').validate({
rules: {
test: {
required: true
},
myselect: {
required: true
}
}
});
$('select[name="myselect"]').on('change', function () {
if ($(this).val() == 1) {
$('input[name="test"]').rules('add', {
messages: {
required: "this is the new message"
}
});
}
});
});
这篇关于jQuery Validate:使用选择选项更改所需的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!