且构网

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

如何在jQuery验证后禁用/启用“提交"按钮?

更新时间:2022-12-07 09:08:29

您不能禁用click事件上的按钮.因为如果单击按钮时表单仍然无效,则将无法再次单击它.您只能在表单成功通过验证后 禁用它.

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.

为此使用插件的submitHandler选项,因为只有在表单通过验证后,它才会在单击按钮时触发.

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>

注释:

    根据jQuery文档,
  1. $().ready(function() {... 不推荐 >.改用$(document).ready(function() {...$(function() {....

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

当您已经在.validate()中声明了required规则时,就不需要required内联HTML属性.

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

您在setDefaults()中的submitHandler已损坏. signupForm.submit()行将不执行任何操作,因为signupForm是未定义的变量.在.validate()中定义submitHandler并使用开发人员提供的form自变量.

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.

演示: http://jsfiddle.net/6foLxzmc/13/

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