为什么我需要在提交按钮上单击两次才能提交表单?

时间:2015-08-05 05:04:57

标签: jquery forms validation submit mixpanel

我有一个用jquery验证的表单,一旦提交,我想调用一个函数(track_forms函数用Mixpanel跟踪它)。

除了一件事之外,它的工作正常:我必须点击两次按钮才能提交表格。第一次点击不做任何事情。我认为使用submitHandler存在问题,因为问题是在实现之后出现的。

有人知道这个问题是什么吗?

由于

  $.validator.addMethod(
    'ContainsAtLeastOneNumber',
    function (value) { 
        return /[0-9]/.test(value); 
    },  
    'Please enter at least 8 characters containing numbers and letters.'
);

$.validator.addMethod(
    'ContainsAtLeastOneLetter',
    function (value) { 
        return /[a-z]/.test(value); 
    },  
    'Please enter at least 8 characters containing numbers and letters.'
);


$('#signupForm').validate({    
rules: {
    email: {
        required: true,
        email: true
    },
    password: {
        minlength: 8,
        ContainsAtLeastOneNumber: true,
        ContainsAtLeastOneLetter: true,
        required: true
    },
    confirmPassword: {
        required: true,
        equalTo: "#password"
    },
    terms: {
        required: true,
    }
},
messages: {
    email: "Please enter a valid email address.",
    password: {
      required: "Please enter at least 8 characters containing numbers and letters.",
      minlength: "Please enter at least 8 characters containing numbers and letters.",
    },
    confirmPassword: {
      required: "Please enter at least 8 characters containing numbers and letters.",
      equalTo: "The passwords are not matching.",
    },
    terms: {
        required: "You must agree with our Terms of Service.",
    },
},
highlight: function(element) {
    var id_attr = "#" + $( element ).attr("id") + "1";
    $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    $(id_attr).removeClass('glyphicon-ok').addClass('glyphicon-remove');         
},
unhighlight: function(element) {
    var id_attr = "#" + $( element ).attr("id") + "1";
    $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
    $(id_attr).removeClass('glyphicon-remove').addClass('glyphicon-ok');         
},
errorElement: 'span',
    errorClass: 'help-block',
    errorPlacement: function(error, element) {
        if (element.attr('name') == 'terms' ) {
        error.insertAfter(".some-class");
        } else {
        error.insertAfter(element);
        }
    },
submitHandler: function(form) {
 mixpanel.track_forms("#signupForm", "Created Account");
    } 
 });

1 个答案:

答案 0 :(得分:0)

您不应该在track_forms内拨打submitHandler

提交表单时会调用

submitHandler,但调用track_forms时不会跟踪表单是否已提交。

track_forms在表单的submit事件上设置新的处理程序。然后,当您单击提交按钮时,它会触发Mixpanel事件,然后继续表单提交。

现在正是这样:

  1. 表单已提交并经过验证,然后调用submitHandler
  2. submitHandler设置了Mixpanel表单跟踪
  3. ??? [表格提交被阻止]
  4. 您再次点击该按钮,Mixpanel会跟踪它
  5. 我不完全理解第3步中发生了什么,第一种表格没有提交。

    您可以在单击提交按钮之前尝试调用track_forms。但是,使用Mixpanel的track_forms可能会干扰您的验证功能。如果确实如此,最好只跟踪submitHandler内的正常事件,然后等待继续提交,以确保跟踪事件。