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 变量,但它似乎不起作用。有什么帮助吗?

4

2 回答 2

1

Though I'm not completely sure your intentions, it'd have to look something more like:

var norepeat = false;

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

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

Where norepeat is defined in a global scope. Also, remember to use === as opposed to ==. And trimming the string before testing it wouldn't be a horrible idea...

But, wouldn't you want the errors to still persist if the user hasn't corrected them - isn't that the point of validation?

于 2012-11-14T04:09:23.183 回答
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;
        }
    }
于 2012-11-14T04:21:22.147 回答