首页 > 解决方案 > Javascript 表单 onsubmit 总是在刷新时运行

问题描述

我在提交表单时遇到问题 - 不知何故,当用户没有单击提交按钮时,在刷新页面时,验证运行并且错误消息显示在页面上。

任何人都知道为什么 onsubmit 在这里不起作用,我如何只在表单提交上显示错误?

HTML:

 <form action="#" method="POST" name="signupForm" class="ggForm" onsubmit="return validateSignupForm()">
   
<div class="email">
  <label for="emailBox">Email*:</label>
  <input type="email" name="custEmail" id="emailBox" placeholder="john.doe@gmail.com" required
pattern="^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" title="(The email entered is invalid)">
                </div>
   
   <!-- submit button below -->
   <div>
     <input type="submit" value="Submit Form">
   </div>

   <p id="potentialErrors"></p>
</form>

JS:

window.onload = init;

function init() {
  document.forms["signupForm"].onsubmit = validateSignupForm();
}

function validateSignupForm() {
    console.log("ran");
    var errMsg = "";

    var email = document.forms["signupForm"]["custEmail"].value;
    if (email == "") {
        errMsg += "<br>Email must be filled out";
    }

    // when there's errors in any field, put as message below submit button
    if (errMsg != "") {
        document.getElementById("potentialErrors").innerHTML = errMsg;

        //change the error message css
        $("p#potentialErrors").css("height","50"); 
        $("p#potentialErrors").attr("width","500"); 
        $("p#potentialErrors").css("font-weight","bold");
        $("p#potentialErrors").css("color","red"); 

        return false;
    }
    return true;
}

编辑仅供参考:我已将上述代码编辑到此 codepen 中,它现在正在工作: https ://codepen.io/vadevalor/pen/VwepxdY

  1. 需要添加jquery库,
  2. 需要删除html验证
  3. 根据this question的评论,需要在js函数中删除()

标签: javascripthtmljqueryvalidation

解决方案


您需要onsubmit在表单event.preventDefault();中添加,接下来将 jquery 库添加到您的代码中。

所以:

<script
  src="https://code.jquery.com/jquery-3.5.1.js"
  integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
  crossorigin="anonymous"></script>
<form action="#" method="POST" name="signupForm" class="ggForm" onsubmit="event.preventDefault(); return validateSignupForm()">

推荐阅读