HTML text input allow only numeric input

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

    <input type="text" onkeydown="validateNumber(event);"/ >
    
    0 讨论(0)
  • 2020-11-21 05:27

    JavaScript code:

    function validate(evt)
    {
        if(evt.keyCode!=8)
        {
            var theEvent = evt || window.event;
            var key = theEvent.keyCode || theEvent.which;
            key = String.fromCharCode(key);
            var regex = /[0-9]|\./;
            if (!regex.test(key))
            {
                theEvent.returnValue = false;
    
                if (theEvent.preventDefault)
                    theEvent.preventDefault();
                }
            }
        }
    

    HTML code:

    <input type='text' name='price' value='0' onkeypress='validate(event)'/>
    

    works perfectly because the backspace keycode is 8 and a regex expression doesn't let it, so it's an easy way to bypass the bug :)

    0 讨论(0)
  • 2020-11-21 05:28

    Please find below mentioned solution. In this user can be able to enter only numeric value, Also user can not be able to copy, paste, drag and drop in input.

    Allowed Characters

    0,1,2,3,4,5,6,7,8,9
    

    Not allowed Characters and Characters through events

    • Alphabetic value
    • Special characters
    • Copy
    • Paste
    • Drag
    • Drop

    $(document).ready(function() {
      $('#number').bind("cut copy paste drag drop", function(e) {
          e.preventDefault();
      });     
    });
    function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
        return true;
    }
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input type="text" class="form-control" name="number" id="number" onkeypress="return isNumberKey(event)" placeholder="Enter Numeric value only">

    Let me know if it not works.

    0 讨论(0)
  • 2020-11-21 05:28

    A short and sweet implementation using jQuery and replace() instead of looking at event.keyCode or event.which:

    $('input.numeric').live('keyup', function(e) {
      $(this).val($(this).val().replace(/[^0-9]/g, ''));
    });
    

    Only small side effect that the typed letter appears momentarily and CTRL/CMD + A seems to behave a bit strange.

    0 讨论(0)
  • 2020-11-21 05:29

    One more example where you can add only numbers in the input field, can not letters

    <input type="text" class="form-control" id="phone" name="phone" placeholder="PHONE" spellcheck="false" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">
    
    0 讨论(0)
  • 2020-11-21 05:30

    Most answers here all have the weakness of using key- events.

    Many of the answers would limit your ability to do text selection with keyboard macros, copy+paste and more unwanted behavior, others seem to depend on specific jQuery plugins, which is killing flies with machineguns.

    This simple solution seems to work best for me cross platform, regardless of input mechanism (keystroke, copy+paste, rightclick copy+paste, speech-to-text etc.). All text selection keyboard macros would still work, and it would even limit ones ability to set a non-numeric value by script.

    function forceNumeric(){
        var $input = $(this);
        $input.val($input.val().replace(/[^\d]+/g,''));
    }
    $('body').on('propertychange input', 'input[type="number"]', forceNumeric);
    
    0 讨论(0)
提交回复
热议问题