我不明白我在这里做错了什么....尝试了几乎所有的表格仍然没有经过验证提交。我不知道造成问题的原因是这里过去4个小时一直在研究这个问题,每次我点击提交按钮就会直接进入提交成功页面......有人可以帮我这个吗?
<script type ="text/javascript">
function validate(){
if(document.orderForm.firstName.value=="" ){
document.getElementById('errors').innerHTML = "Please Enter a First Name";
document.orderForm.fistName.focus();
return (false);
}
if(document.orderForm.lastName.value == "" ){
document.getElementById('errors').innerHTML = "Please Enter a Last Name";
document.orderForm.lastName.focus();
return (false);
}
if(document.orderForm.address.value == "" ){
document.getElementById('errors').innerHTML = "Please Enter a address");
document.orderForm.address.focus();
return (false);
}
if(document.orderForm.city.value == "" ){
document.getElementById('errors').innerHTML = "Please Enter a City");
document.orderForm.city.focus();
return (false);
}
if(document.orderForm.postalCode.value == "" ||
document.orderForm.postalCode.value.length != 6 ){
document.getElementById('errors').innerHTML = "Please Enter a correct PostalCode");
document.orderForm.postalCode.focus();
return (false);
}
if(document.orderForm.province.value == "Select" ){
document.getElementById('errors').innerHTML = "Please Select your province")
return (false);
}
if(document.orderForm.widget1qty.value == "0" || document.orderForm.widget1qty.value == "" &&
document.orderForm.widget2qty.value == "0" || document.orderForm.widget2qty.value == "" &&
document.orderForm.widget2qty.value == "0" || document.orderForm.widget2qty.value == "" ){
document.getElementById('errors').innerHTML = "Please Select at least one item")
return (false);
}
else
{
return(true);
}
}
</script>
<form name="orderForm" method="POST" action="processForm.html" onSubmit="return validate();">
答案 0 :(得分:2)
参考此示例代码,绝对解决您的问题
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
function validate()
{
if( document.myForm.Name.value == "" )
{
document.getElementById("errors").innerHTML = "Please enter first name";
document.myForm.Name.focus() ;
return false;
}
return( true );
}
//-->
</script>
</head>
<body>
<form action="processForm.html" name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
<div id="errors"></div>
</body>
</html>
答案 1 :(得分:-2)
请使用以下代码。它工作正常。
function validate() {
if (document.orderForm.firstName.value=="" ) {
document.getElementById("errors").innerHTML = `Please enter first name`;
document.getElementById("firstName").focus();
return (false);
}
}
<form name="orderForm" onSubmit="return validate();">
<input type="text" id="firstName" />
<input type="submit" id="btnSubmit" value="submit" />
<div id="errors"></div>
</form>