我正在尝试使用getElementById
来验证数量和价格都是整数。任何故障排除帮助将不胜感激。我还在 HTML 中创建了几个输入。
<body>
<section>
<p><input name="quantity" type="text" id="quantity"
placeholder="quantity" autofocus></p>
<p><input name="price" type="text" id="price" placeholder="price"></p>
</section>
<script>
quantity.addEventListener("blur", validate, false);
price.addEventListener("blur", validate, false);
function validate() {
box = this.id;
data = this.value;
thequantity = document.getElementById("quantity");
theprice = document.getElementById("price");
thetotal = document.getElementById("total");
if (data) {
error1 = thequantity.value.match(/[0-9\.]/);
error2 = thequantity.value.match(/[0-9\.]/);
if (!error1 && !error2) {
alert("Please enter a number");
price = Number(theprice.value);
quantity = Number(thequantity.value);
thetotal.value = thequantity.value * theprice.value;
}
if (error1) {
alert("Please enter a number");
document.getElementById(box).value = "";
}
if (error2) {
alert("Please enter a number");
document.getElementById(box).value = "";
}
} else {
var num = box.value(/[0-9]/);
document.getElementById(box).value = thetotal;
}
}
</script>
最佳答案
只需检查转换为数字是否不会导致 NaN
:
if (isNaN(Number(document.getElementById("quantity").value))) {
alert("Please enter a number.");
}
关于javascript - 使用 getElementById 验证函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52920801/