How can I disable/enable submit button after jQuery Validation?

前端 未结 2 860
执笔经年
执笔经年 2020-12-01 21:18

I want to disable the submit button of the form after the \"on_click\" event, this jscript does it succesfully, but when a incorrect email is validated with jquery and then

相关标签:
2条回答
  • 2020-12-01 21:56

    You cannot disable the button on the click event; because if the form is still invalid when you click the button, you will not be able to click it again. You can only disable it after the form has successfully passed validation.

    Use the plugin's submitHandler option for this as it's fired on a button click only when the form has passed validation.

    <script>
    $(document).ready(function() {
    
        $("#signupForm").validate({
            wrapper: "div",
            rules: {
                email: {
                    required: true,
                    email: true
                },
                password: {
                    required: true,
                    minlength: 5
                }
            },
            messages: {
                email: "Use una cuenta de correo v&aacute;lida",
                password: {
                    required: "Ingrese su contraseña",
                    minlength: "La contrase&ntilde;a al menos debe tener 5 caracteres"
                }
            },
            submitHandler: function(form) { // <- pass 'form' argument in
                $(".submit").attr("disabled", true);
                form.submit(); // <- use 'form' argument here.
            }
        });
    
    });
    </script>
    

    NOTES:

    1. $().ready(function() {... is not recommended as per jQuery documentation. Use $(document).ready(function() {... or $(function() {... instead.

    2. You do not need the required inline HTML attribute when you've already declared the required rule within .validate().

    3. Your submitHandler within setDefaults() was broken. The signupForm.submit() line will do nothing because signupForm is an undefined variable. Define submitHandler within .validate() and use the form argument as provided by the developer.

    DEMO: http://jsfiddle.net/6foLxzmc/13/

    0 讨论(0)
  • 2020-12-01 22:06

    Bind to the submit event instead of to the button click.

    $('#signupForm').submit(function(){
       $(this).find('.submit').prop('disabled',true);
    });
    

    Alternatively do the disabling in submitHandler option of plugin

    0 讨论(0)
提交回复
热议问题