且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery Validate插件,在表单有效时启用提交按钮

更新时间:2022-10-25 09:33:31

您只需构造一个blur(甚至是keyup)处理程序函数即可根据表单的有效性来切换按钮.使用插件的.valid()方法测试表单.

$('input').on('blur', function() {
    if ($("#myform").valid()) {
        $('#submit').prop('disabled', false);  
    } else {
        $('#submit').prop('disabled', 'disabled');
    }
});

演示: http://jsfiddle.net/sd88wucL/ >


相反,您还可以使用 both 事件来触发相同的处理函数...

$('input').on('blur keyup', function() {
    if ($("#myform").valid()) {
        $('#submit').prop('disabled', false);  
    } else {
        $('#submit').prop('disabled', 'disabled');
    }
});

演示2: http://jsfiddle.net/sd88wucL/1/

来源: https://***.com/a/21956309/594235

I have an enabled and disabled state for the submit button on my form.

The conditions are as follows:

If all input fields have been entered and are valid enable the submit button.

If some fields have not been entered do not enable the submit button.

So far the validation is being done within the onkeyup event and is only working for the first input:

//Custom onkeyup validation
            onkeyup: function(element) {
                //Check if input is empty remove valid class from parent
                var formInput = $(element),
                    formInputParent = $(element).parent('fieldset');
                if(formInputParent.hasClass('form--valid') && formInput.val() === "") {
                    formInputParent.removeClass('form--valid');
                }

                //Check if all fields are not empty to remove submit--disabled class
                var formInputs = $('form').find(':input');
                console.log(formInputs);

                formInputs.each(function(){
                    if(formInputs.length > 0) {
                        formInputs.parents('form').find('.submit-form').removeClass('submit--disabled');
                    } 
                });

            }

Check here for a DEMO

You would simply construct a blur (or even a keyup) handler function to toggle the button based on the form's validity. Use the plugin's .valid() method to test the form.

$('input').on('blur', function() {
    if ($("#myform").valid()) {
        $('#submit').prop('disabled', false);  
    } else {
        $('#submit').prop('disabled', 'disabled');
    }
});

DEMO: http://jsfiddle.net/sd88wucL/


Instead, you could also use both events to trigger the same handler function...

$('input').on('blur keyup', function() {
    if ($("#myform").valid()) {
        $('#submit').prop('disabled', false);  
    } else {
        $('#submit').prop('disabled', 'disabled');
    }
});

DEMO 2: http://jsfiddle.net/sd88wucL/1/

Source: https://***.com/a/21956309/594235