我可以在这里看到提醒信息。即使在返回false之后,我也可以看到我的表单发布了它。代码在哪里被破坏了?
function ValidateForm(){
var productName = document.addProduct.product_name;
var partNumber = document.addProduct.part_number;
var description = document.addProduct.description;
var price = document.addProduct.price;
var formelements = [productName, partNumber, description, price];
formelements.forEach(function(obj) {
if(obj.value=="") {
obj.style.borderColor = "#FF0000";
alert(obj);
return false;
}
});
我的HTML代码
<form action="product_formhandler.php" name="addProduct" id="addProduct" onsubmit="return ValidateForm();" method="post">
<table>
<tr>
<td>
Product Name:
</td>
<td>
<input type="text" id="product_name" name="product_name" />
</td>
</tr>
<tr>
<td>
Part number:
</td>
<td>
<input type="text" id="part_number" name="part_number" />
</td>
</tr>
<tr>
<td>
Description:
</td>
<td>
<textarea id="description" name="description" rows="8" col="25"></textarea>
</td>
</tr>
<tr>
<td>
Price:
</td>
<td>
<input type="text" id="price" name="price" />
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<input type="reset" id="reset" value="Reset" />
<input type= "hidden" name="addproduct" value="1" />
<input type="submit" id="addProductSubmit" name="action" value="Add" />
</td>
</tr>
</table>
</form>
答案 0 :(得分:2)
函数ValidateForm
没有return
语句。您唯一拥有的是您传递给forEach
forEach
true
)if (condition) { retVal = false; }
而没有else
)这样:
var retVal = true;
formelements.forEach(function(obj) {
if(obj.value=="") {
obj.style.borderColor="#FF0000";
alert(obj);
retVal = false;
});
return retVal;
或者,使用传统的for循环:
for (var i = 0; i < formelements.length; i++) {
var obj = formelements[i];
if (obj.value == "") {
obj.style.borderColor="#FF0000";
alert(obj);
return false;
}
}
虽然一旦发现单个故障,此方法将停止。
答案 1 :(得分:0)
您从false
循环返回forEach
,不您的验证功能。你需要做这样的事情:
/* Declare variable outside of loop which is set to true by default */
var forEachResult = true;
formelements.forEach(function(obj) {
if(obj.value=="") {
obj.style.borderColor="#FF0000";
alert(obj);
/* Rather than returning false, set the variable to false instead. */
forEachResult = false;
/* Break the loop. */
return;
}
/* Return the variable which will either be true or false. */
return forEachResult;
答案 2 :(得分:-1)
function ValidateForm(){
var productName=document.addProduct.product_name;
var partNumber=document.addProduct.part_number;
var description=document.addProduct.description;
var price=document.addProduct.price;
var formelements =[productName, partNumber, description, price];
var isValid = true;
formelements.forEach(function(obj) {
if(obj.value=="") {
obj.style.borderColor="#FF0000";
alert(obj);
isValid = false;
return false;
}
});
return isValid;
}