javascript - 表单字段提交
问题描述
我有我的 HTML 和 JS,我将如何在我的 JS 中使用此表单,因此如果未输入其中一个字段,则表单不会提交并显示我的原件请输入所有字段错误
形式:
<form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
HTML:
<!doctype html>
<html lang="en">
<head>
<title> Forms </title>
<style>
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
</style>
<meta charset="utf-8">
<script src="prototype.js"></script>
<script src="forms.js"></script>
</head>
<body>
<h1> Keyboard Events and Form Submit </h1>
<!-- Form -->
<form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
<p> <span>Name:</span> <input id="input1" value="" placeholder="Enter Name" name="Name"></p>
<p> <span>Id:</span> <input id="input2" value=""
placeholder="Enter ID" name="ID"></p>
<p> <span>Email:</span> <input id="input3" value="" placeholder="Enter Email" name="Email"></p>
<p>
<button id="submitButton" type="button" onclick="submit()"> Submit </button>
<button id="resetButton" type="button" onclick="reset()"> Reset </button>
</p>
<p style="color:red" id="ErrorMessage"> </p>
</body>
</html>
JS:
function reset(){
document.getElementById('input1').value = "";
document.getElementById('input2').value = "";
document.getElementById('input3').value = "";
document.getElementById('ErrorMessage').innerHTML = "";
}
function submit(){
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if(inp1 == "" || inp2 == "" || inp3 == "")
{
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
}
else{
//do your code here
document.getElementById('ErrorMessage').innerHTML = "";
}
}
解决方案
将按钮类型更改为“提交”并在 onsubmit 事件处理程序中进行验证:
<form onsubmit="return validateMethod()" />
将所有验证逻辑移入 validateMethod,如果验证失败则返回 false。
下面是一个示例,但我认为您应该为此使用 jquery 库:
function validateMethod(){
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if(!inp1 || !inp2 || !inp3)
{
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
return false;
}
else{
//do your code here
document.getElementById('ErrorMessage').innerHTML = "";
return true;
}
}
推荐阅读
- assembly - ARM 程序集无法从地址加载
- html - html-验证时输入背景颜色更新
- laravel - Laravel Homestead 有多个实例,其中一个说明站点无法访问
- c# - 从接口执行 EF_context.Database.ExecuteSqlRawAsync
- visual-studio-code - 如何让 Prettier 使用自动保存并保留重做日志
- android - Jetpack Compose Vertical Grid 单项跨度大小
- bash - 用于计数/验证管道的正则表达式
- facebook - 如何通过调用 Graph API 获取 facebook 用户元数据?
- wpf - 工具栏中的标签前景
- sql - 用于检查列值的唯一性的 SQL 查询