javascript - 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
- 需要添加jquery库,
- 需要删除html验证
- 根据this question的评论,需要在js函数中删除()
解决方案
您需要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()">
推荐阅读
- reactjs - 使用 create-react-app 运行自定义打字稿脚本时遇到问题
- python - 在 python 中使用正则表达式识别字符串中的模式
- mysql - 在 Rails 中加入具有活动存储的多个表
- asp.net-mvc - dotnet core 在 Github 操作中访问环境变量
- javascript - 如何在 NestJS 中实现多个 .env.{ENVIRONMENT}
- geojson - 无法使用以下驱动程序打开数据源“multipolygons”
- javascript - 我可以在HTML和CSS之前直接学习Javascript吗
- datastage - 如何在 DataStage 中全局添加 Alter session 语句,而不是触摸每个作业并在 sql 语句之前写入?#ibm 数据阶段
- performance - Locust 如何从响应中提取值然后用于下一个序列请求
- python - 迭代所有列 Pandas Dataframe 并比较备用列