javascript - 使用 getElementById 验证函数

标签 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>

最佳答案

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

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

关于javascript - 使用 getElementById 验证函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52920801/

相关文章:

javascript - 无法看到 MapBox React Native GL 注释

javascript - document.getSelection 在选择中带有回车符

javascript - 在 $.get 之后更改属性

c# - 用于验证多个电子邮件地址的正则表达式

c++ - 如何验证用户输入的月份输入日期?

javascript - 如何修复 React Context 的对象不是函数 - TypeError

javascript - 默认选择选项

html - IE 始终以 TD 居中文本

html - Bootstrap Mobile Menu子菜单克拉不可见

ruby-on-rails - 创建 mongoid Rails 后跳过验证