有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?


当前回答

希望我不是用一个丑陋的棍子在这里打死马,但我用这个为我的网站数量输入,它只允许从1到99的数字。

试一试: https://jsfiddle.net/83va5sb9/

      <input min="1" type="text" id="quantity" name="quantity" value="1"
      onKeyUp="numbersonly()">

      <script>
    function numbersonly() {
      var str = document.getElementById("quantity").value
      var newstr = ""
      for (i = 0; i < str.length; i++) {
        for (ii = 1; ii < 10; ii++) {
          if (str.charAt(i).indexOf(ii) > -1) {
            newstr += str.charAt(i)
          }
        }
      }
      if (newstr == "") {
        newstr = 1
      }
      if (parseInt(newstr) > 99) {
        newstr = 99
      }
      document.getElementById("quantity").value = newstr
    }

    </script>

其他回答

JavaScript

function validateNumber(evt) {
    var e = evt || window.event;
    var key = e.keyCode || e.which;

    if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
    // numbers   
    key >= 48 && key <= 57 ||
    // Numeric keypad
    key >= 96 && key <= 105 ||
    // Backspace and Tab and Enter
    key == 8 || key == 9 || key == 13 ||
    // Home and End
    key == 35 || key == 36 ||
    // left and right arrows
    key == 37 || key == 39 ||
    // Del and Ins
    key == 46 || key == 45) {
        // input is VALID
    }
    else {
        // input is INVALID
        e.returnValue = false;
        if (e.preventDefault) e.preventDefault();
    }
}

你可以添加逗号,句号和减号(,.-)

  // comma, period and minus, . on keypad
  key == 190 || key == 188 || key == 109 || key == 110 ||

HTML

<input type="text" onkeydown="validateNumber(event);"/ >

2个解决方案:

使用表单验证器(例如jQuery验证插件)

在输入字段的onblur事件期间(即当用户离开字段时)执行检查,使用正则表达式:

<script type="text/javascript">
function testField(field) {
    var regExpr = new RegExp("^\d*\.?\d*$");
    if (!regExpr.test(field.value)) {
      // Case of error
      field.value = "";
    }
}

</script>

<input type="text" ... onblur="testField(this);"/>

我选择使用这里提到的两个答案的组合,即。

<输入类型=“编号”/>

and

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode
    return !(charCode > 31 && (charCode < 48 || charCode > 57));
}

<input type=“text” onkeypress=“return isNumberKey(event);”>

下面的函数将检查每个输入字符是否为number。

numeric: value => {
    let numset = new Set(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']);
    console.log(numset.has(value.substring(value.length - 1, value.length)));
}

这是我的一句话解决方案!

$('#input-field').keypress(e => !String.fromCharCode(e.which).match(/\D/g));