Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validate plugin, enable submit button when form is valid

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

like image 234
Filth Avatar asked Nov 20 '14 20:11

Filth


1 Answers

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://stackoverflow.com/a/21956309/594235

like image 196
Sparky Avatar answered Jan 02 '23 08:01

Sparky