【问题标题】:jQuery Validate: submitHandler submits form without hitting form.submitjQuery Validate:submitHandler 提交表单而不点击 form.submit
【发布时间】:2013-08-06 14:43:22
【问题描述】:

jQuery Validate 正在工作(当必填电子邮件字段为空时触发错误),但 submitHandler 中的代码未触发(不显示警报)。而且由于 submitHandler 不工作,我不希望表单发布到 secure/process_login.php,因为 form.submit();在不工作的 alert() 之后,但如果它验证它就会这样做。

表格代码:

<form action="secure/process_login.php" method="post" id="login_form" name="login_form">
  <fieldset>
    <legend>Log In</legend>
    <div class="form-group">
      <label for="inputEmail">Email address</label>
      <input type="text" id="email" class="form-control" name="email"placeholder="Your Email Address" required>
    </div>
    <div class="form-group">
      <label for="inputPassword">Password</label>
      <input type="password" class="form-control" name="password" id="password" placeholder="Your Password">
      <input type="hidden" name="p" id="p" value="">
    </div>
    <button type="submit" class="btn btn-primary form-control">Log In</button>
  </fieldset>
</form>

脚本:

<script>
  $("#login_form").validate({
  submitHandler: {
    function formhash(form, password) {
       // Create a new element input, this will be out hashed password field.
       var p = document.createElement("input");
       // Add the new element to our form.
       form.appendChild(p);
       p.name = "p";
       p.type = "hidden"
       p.value = hex_sha512(password.value);
       // Make sure the plaintext password doesn't get sent.
       password.value = "";
       // Finally submit the form.
       alert("Test");
       form.submit();
    }
  }
  });
</script>

【问题讨论】:

    标签: jquery jquery-plugins jquery-validate


    【解决方案1】:

    您的 JS 中有语法错误。您不需要将 formhash 函数包装在大括号中。试试这个:

    $("#login_form").validate({
        submitHandler: function formhash(form, password) {
            //submit code
        }
    });
    

    【讨论】:

    • 感谢菲尔的回复。我改变了它并再次尝试。有趣的是,现在验证的外观和感觉发生了变化(纯文本与漂亮的盒子)。但其余部分保持不变,不会触发警报,并且无论如何都会发布表单。
    • 我复制了您的确切代码,应用了我的修复程序,它为我在本地运行。如果没有修复,我看到了语法错误
    • 您的脚本标签是在表单 HTML 之前还是之后?如果是在您需要将其包装在 $(document).ready(function() {}) 之后
    • 您还收到表单发布前的警报吗?我有你的代码(里面有我的),但警报没有触发。
    【解决方案2】:

    您必须将loginform 设置为表单标签的id 属性。当您使用 $('#loginform') 作为选择器时。

    【讨论】:

    • &lt;form action="secure/process_login.php" method="post" name="login_form"&gt; 更改为 &lt;form action="secure/process_login.php" method="post" id="login_form" name="login_form"&gt; 会导致相同的行为。
    猜你喜欢
    • 2017-04-26
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 2017-05-09
    相关资源
    最近更新 更多