我正在尝试创建一个脚本,它将接受 2 个输入并计算总和。我希望在计算发生之前验证两个输入 - 输入必须在 0 到 10 之间。
但是,当我在两个字段中输入超过 10 的值(例如 50)时,我只会收到一个验证错误,而不是两个。
有什么问题吗?
function calc() {
var x, y, z, text1, text2;
// Get the value of the input field with id="numb"
x = Number(document.getElementById("val01").value);
y = Number(document.getElementById("val02").value);
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 0 || x > 10) {
text1 = "Input not valid";
document.getElementById("validation1").innerHTML = text1;
} else if (isNaN(y) || y < 0 || y > 10) {
text2 = "Input not valid";
document.getElementById("validation2").innerHTML = text2;
} else {
z = x + y;
document.getElementById("total").innerHTML = z;
}
}
<p>Please input a number between 0 and 10:</p>
1st number:<input id="val01" required> <b id="validation1"></b> <br>
2nd Number:<input id="val02" required> <b id="validation2"></b> <br>
<button onclick="calc()">click</button><br /> sum = <span id="total">0</span>
最佳答案
您可以使用标志并检查它以进行计算。
跳过 else
部分并使用标志代替。
var ok = true;
if (isNaN(x) || x < 0 || x > 10) {
ok = false;
text1 = "Input not valid";
document.getElementById("validation1").innerHTML = text1;
}
if (isNaN(y) || y < 0 || y > 10) {
ok = false;
text2 = "Input not valid";
document.getElementById("validation2").innerHTML = text2;
}
if (ok) {
z = x + y;
document.getElementById("total").innerHTML = z;
}
关于javascript - 输入验证只工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40683996/