问题
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.
I try my methods using the change function for the select input like so:
$('#selector').change(function(){
Method X;
}
Methods I've tried:
$.validator.messages.required = "New Message";$('#inputx').rules("remove", "required");$('#inputx').rules("add", { messages: {required: "New Message"}});
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;
}
}
The error message does not change even after unfocusing the #inputx element
EDIT: I did an incorrect conditional statement inside my onChange. Everything works perfectly now!
回答1:
The .rules('add') method is working fine for me...
http://jsfiddle.net/2NJS7/
$(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"
}
});
}
});
});
来源:https://stackoverflow.com/questions/21717521/jquery-validate-change-required-message-using-select-option