所以我有一个HTML表单,当我按下一个键并且默认内容也被删除时,我需要清除表单输入。如果单击了reset,则表单将重置为其默认的“ Enter ect”,并且您必须再次输入一些内容。另外,如果在没有输入任何字段的情况下单击了提交,它将显示一个错误,指出我的一个字段为空,我该如何使用JS做到这一点?
我尝试使用JS清除默认表单,但是所有这些表单都会立即被删除,而不是被单击的表单。
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="formsubmit.js"></script>
</head>
<body>
<h1> Task 2: Keyboard Events and Form Submit </h1>
<p> <span>Name:</span> <input id="input1" value="Enter Name" name="Name"></p>
<p> <span>Id:</span> <input id="input2" value="Enter ID" name="ID"></p>
<p> <span>Email:</span> <input id="input3" value="Enter Email" name="Email"></p>
<p>
<button id="submitButton" type="button"> Submit </button>
<input type="reset" value="Reset">
</p>
<p style="color:red" id="ErrorMessage"> </p>
</form>
</body>
</html>
JS:
window.onload=function(){
document.getElementById('input1').value = "";
document.getElementById('input2').value = "";
document.getElementById('input3').value = "";
}
答案 0 :(得分:2)
<!doctype html>
<html lang="en">
<head>
<title> Forms </title>
<script>
//window.onload = Reset();
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 = "";
}
}
</script>
<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="formsubmit.js"></script>
</head>
<body>
<h1> Task 2: Keyboard Events and Form Submit </h1>
<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>