簡體   English   中英

Javascript 表單 onsubmit 始終在刷新時運行

[英]Javascript form onsubmit always runs on refresh

我在提交表單時遇到問題 - 不知何故,當用戶沒有點擊提交按鈕時,在刷新頁面時,驗證運行並且錯誤消息顯示在頁面上。

任何人都知道為什么 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;
}

編輯僅供參考:我已將上述代碼編輯到此代碼筆中,它現在正在工作: https://codepen.io/vadevalor/pen/VwepxdY

  1. 需要添加jquery庫,
  2. 需要刪除 html 驗證
  3. 根據對此問題的評論,需要刪除 js function 中的 ()

您需要在表單event.preventDefault();中添加onsubmit ,接下來將 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()">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM