我在html页面中有一个表单,在我单击提交按钮后最终被清除。我想知道如何在用户需要修复任何错误的情况下点击提交后如何使数据保留在表单中。任何帮助将不胜感激!
这是html代码:
<form id = "contactform" action = "">
<label> Name:
<input name = "firstname" type = "text" id = "firstname" maxlength = "50"/>
</label>
<label> Last Name:
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
<label> Address:
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
<label> Postcode:
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
<input type = "submit" value = "Submit" onclick = "validate()" />
<input type = "reset" value = "Clear" />
</p>
</form>
这里是javascript代码:
function validate() {
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');
if(firstname.value == "") {
alert("Make sure the first name field is filled");
return false;
}
if(lastname.value == "") {
alert("Make sure the last name field is filled");
return false;
}
if(address.value == "") {
alert("Make sure the address field is filled");
return false;
}
if(postcode.value == "") {
alert("Make sure the post code field is filled");
return false;
}
答案 0 :(得分:0)
使用onclick return
onclick="return validate()"
function validate() {
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');
if (firstname.value == "") {
alert("Make sure the first name field is filled");
return false;
}
if (lastname.value == "") {
alert("Make sure the last name field is filled");
return false;
}
if (address.value == "") {
alert("Make sure the address field is filled");
return false;
}
if (postcode.value == "") {
alert("Make sure the post code field is filled");
return false;
}
}
<form id="contactform" action="">
<label> Name:
<input name = "firstname" type = "text" id = "firstname" maxlength = "50"/>
</label>
<label> Last Name:
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
<label> Address:
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
<label> Postcode:
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
<input type="submit" value="Submit" onclick="return validate()" />
<input type="reset" value="Clear" />
</form>
答案 1 :(得分:0)
首先,在表单中添加一个提交处理程序:
<form id="contactform" action = "" onsubmit="handleSubmit()">
...
</form>
然后在您的处理程序中验证输入。如果它无效,则需要使用preventDefault()来停止提交表单。 注意:如果没有错误,您必须在return true
结尾处validate()
。我在问题中没有看到。
function handleSubmit(event) {
if(!validate()) {
event.preventDefault();
}
return;
}