jQuery Validate: Change required message using select option

此生再无相见时 提交于 2019-12-25 02:08:35

问题


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:

  1. $.validator.messages.required = "New Message";

  2. $('#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

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