HTML text input allow only numeric input

前端 未结 30 3427
孤街浪徒
孤街浪徒 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:27

    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();
        }
    }
    

    additional you could add comma, period and minus (,.-)

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

    HTML

    
    

提交回复
热议问题