HTML text input allow only numeric input

前端 未结 30 3432
孤街浪徒
孤街浪徒 2020-11-21 04:58

Is there a quick way to set an HTML text input () to only allow numeric keystrokes (plus \'.\')?

30条回答
  •  抹茶落季
    2020-11-21 05:18

    A safer approach is checking the value of the input, instead of hijacking keypresses and trying to filter keyCodes.

    This way the user is free to use keyboard arrows, modifier keys, backspace, delete, use non standard keyboars, use mouse to paste, use drag and drop text, even use accessibility inputs.

    The below script allows positive and negative numbers

    1
    10
    100.0
    100.01
    -1
    -1.0
    -10.00
    1.0.0 //not allowed
    

    var input = document.getElementById('number');
    input.onkeyup = input.onchange = enforceFloat;
    
    //enforce that only a float can be inputed
    function enforceFloat() {
      var valid = /^\-?\d+\.\d*$|^\-?[\d]*$/;
      var number = /\-\d+\.\d*|\-[\d]*|[\d]+\.[\d]*|[\d]+/;
      if (!valid.test(this.value)) {
        var n = this.value.match(number);
        this.value = n ? n[0] : '';
      }
    }

    EDIT: I removed my old answer because I think it is antiquated now.

提交回复
热议问题