2012-11-14 40 views
1

我试图做一个页面的JavaScript出来的错误。我对这一切都很陌生,所以请耐心等待。仅显示“所有项目都必须填写”一次

我有一个表格,当你按下提交,我有以下位,看看是否字段为空:

function calculatePrice() 
{ 

var GasPrice = document.getElementById("number1").value; 
var Distance = document.getElementById("number2").value; 
var Mileage = document.getElementById("number3").value; 
var norepeat = false; 

if (norepeat==false && (GasPrice =="" || Distance =="" || Mileage =="")) 
{ 
var para=document.createElement("p"); 
para.setAttribute("class", "error"); 
var node=document.createTextNode("All fields must be completed"); 
para.appendChild(node); 
var element=document.getElementById("content"); 
element.appendChild(para); 
var norepeat = true; 
} 

我创造了误差时出现的段落标记。问题是,当我按下多次提交时,它每次都会写入错误消息。我尝试了norepeat可变的东西,但它似乎并没有工作。任何帮助?

+0

您正在重置norepeat每个函数调用。如果将变量声明移到函数外部,它可能会按照您的预期工作。 – numbers1311407

回答

1

虽然我不能完全肯定你的意图,它不得不寻找更多的东西一样:

var norepeat = false; 

function calculatePrice() { 
    if(!norepeat && (/* other conditions here */)) { 
     norepeat = true; 
    } 

    return !(/* other conditions above */); 
} 

norepeat在全局范围定义。另外,请记住使用===而不是==。与测试前修剪字符串不会是一个可怕的想法...

但是,就不是你想要的错误仍然存​​在,如果用户没有纠正他们 - 不确认的该点?

+0

他在做它的方式,该错误可能不会消失,直到提交表单,离开页面。 – numbers1311407

+0

@eshellborn我不确定你是否意识到,但'var'关键字声明一个变量。重新指定其值时,不要再写'var'。 – numbers1311407

+0

@ numbers1311407是你回答我的最后一个问题出现,或暗示我应该包括'返回false;'? – jeremy

0

我想你正在尝试做的是这样的。这假定你添加一个新的div“myError”来保存你的错误信息。如果验证未通过,您还需要考虑不要提交表单。

function calculatePrice() { 

     var GasPrice = document.getElementById("number1").value; 
     var Distance = document.getElementById("number2").value; 
     var Mileage = document.getElementById("number3").value; 
     var error = document.getElementById("myError"); 

     if (GasPrice == "" || Distance == "" || Mileage == "") { 
      error.style.display = "block"; 
      return false; 
     } 
     else { 
      error.style.display = "none"; 
      return true; 
     } 
    } 
相关问题