使用getElementById

时间:2018-10-21 23:36:20

标签: javascript html validation

我正在尝试使用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>

1 个答案:

答案 0 :(得分:1)

只需检查是否转换为数字不会导致NaN

if (isNaN(Number(document.getElementById("quantity").value))) {
    alert("Please enter a number.");
}