Best way to restrict a text field to numbers only?

前端 未结 29 1636
长情又很酷
长情又很酷 2020-12-04 22:01

I\'m using the following Javascript to restrict a text field on my website to only accept numerical input, and no other letters or characters. The problem is, it REALLY reje

相关标签:
29条回答
  • 2020-12-04 22:27

    This is a variation on Robert's answer that allows a single decimal point to be entered. If a decimal point has already been entered, only numbers are accepted as input.

    JSFiddle - decimal number input

    // Allow only decimal number input
    
    $('#decimalInput').keypress(function (e) {
        var a = [];
        var k = e.which;
    
        for (i = 48; i < 58; i++)
        a.push(i);
    
        // allow a max of 1 decimal point to be entered
        if (this.value.indexOf(".") === -1) {
            a.push(46);
        }
    
        if (!(a.indexOf(k) >= 0)) e.preventDefault();
    
        $('span').text('KeyCode: ' + k);
    });
    
    0 讨论(0)
  • 2020-12-04 22:29

    I know that there are already many answers but for the sake of simplicity i would like to add another answer which is simple and self explanatory in which we do not have to remember keycodes and it also works across all browsers.

    document.getElementById('myinput').onkeydown = function(e)
     {
         console.log(e.key);
         //console.log(e.target.value);
         switch (e.key)
         {
             case "1":
             case "2":
             case "3":
             case "4":
             case "5":
             case "6":
             case "7":
             case "8":
             case "9":
             case "0":
             case "Backspace":
                 return true;
                 break;
    
             case ".":
                 if (e.target.value.indexOf(".") == -1)
                 {
                     return true;
                 }
                 else
                 {
                     return false;
                 }
                 break;
    
             default:
                 return false;
         }
    
     }
    <input type="text" placeholder="Enter Value" id="myinput" />

    0 讨论(0)
  • 2020-12-04 22:29

    This JavaScript function will be used to restrict alphabets and special characters in Textbox , only numbers, delete, arrow keys and backspace will be allowed. JavaScript Code Snippet - Allow Numbers in TextBox, Restrict Alphabets and Special Characters

    Tested in IE & Chrome.

    JavaScript function

    <script type="text/javascript">
        /*code: 48-57 Numbers
          8  - Backspace,
          35 - home key, 36 - End key
          37-40: Arrow keys, 46 - Delete key*/
        function restrictAlphabets(e){
            var x=e.which||e.keycode;
            if((x>=48 && x<=57) || x==8 ||
                (x>=35 && x<=40)|| x==46)
                return true;
            else
                return false;
        }
    </script>
    

    HTML Source Code with JavaScript

    <html>
        <head>
            <title>JavaScript - Allow only numbers in TextBox (Restrict Alphabets and Special Characters).</title>
            <script type="text/javascript">
                /*code: 48-57 Numbers
                  8  - Backspace,
                  35 - home key, 36 - End key
                  37-40: Arrow keys, 46 - Delete key*/
                function restrictAlphabets(e){
                    var x=e.which||e.keycode;
                    if((x>=48 && x<=57) || x==8 ||
                        (x>=35 && x<=40)|| x==46)
                        return true;
                    else
                        return false;
                }
            </script>
        </head>
    <body style="text-align: center;">
        <h1>JavaScript - Allow only numbers in TextBox (Restrict Alphabets and Special Characters).</h1>
        <big>Enter numbers only: </big>
        <input type="text" onkeypress='return restrictAlphabets(event)'/>
    </body>
    
    </html>
    

    Refrence

    0 讨论(0)
  • 2020-12-04 22:29

    Javascript is often used on the browser client side to perform simple tasks that would otherwise require a full postback to the server. Many of those simple tasks involve processing text or characters entered into a form element on a web page, and it is often necessary to know the javascript keycode associated with a character. Here is a reference.

    Press a key in the text box below to see the corresponding Javascript key code.

            function restrictCharacters(evt) {
    
                evt = (evt) ? evt : window.event;
                var charCode = (evt.which) ? evt.which : evt.keyCode;
                if (((charCode >= '48') && (charCode <= '57')) || (charCode == '44')) {
                    return true;
                }
                else {
                    return false;
                }
            }
    Enter Text:
    <input type="text" id="number" onkeypress="return restrictCharacters(event);" />

    0 讨论(0)
  • 2020-12-04 22:32

    http://jsfiddle.net/PgHFp/

    <html>
    <head>
    <title>Test</title>
    <script language="javascript">
    function checkInput(ob) {
      var invalidChars = /[^0-9]/gi
      if(invalidChars.test(ob.value)) {
                ob.value = ob.value.replace(invalidChars,"");
          }
    }
    </script>
    </head>
    
    <body>
        <input type="text" onkeyup="checkInput(this)"/>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-12-04 22:34

    There is my current solution of numeric input, need to test in different browsers but seems to work

    Support comma and period delimiter (czech native is comma), space and numpad/keyboard numbers input. Allow Ctrl+C Ctrl+A or Ctrl+X, arrow navigation and delete block Ctrl+V. React on escape key by blurring input.

    Watch my Coffee script:

    (($) ->
      $.fn.onlyNumbers = ->
        @each ->
          $(@).keydown (e) ->
            # get code of key
            code = if e.keyCode then e.keyCode else e.which
    
            return $(@).blur() if code is 27 # blur on escape
            return if code in [46, 8, 9, 13] # 46, 8, 9, 27, 13 = backspace, delete, tab, escape, and enter
            return if (e.ctrlKey or e.metaKey) and code in [65, 67, 88] # ctrl|command + [a, c, x]
            return if code in [96..105] # numpad numbers
            return if code in [48..57] # numbers on keyboard
            return if code in [35..39] # 35..39 - home, end, left, right
            return if code in [188, 190, 32] # comma, period, space
            return if code in [44] # comma, period,
    
            e.returnValue = false # IE hate you
            e.preventDefault();
    
          $(@).keypress (e) ->
            code = if e.keyCode then e.keyCode else e.which
            return if code in [44, 46, 32] # comma, period, space
            return if code in [48..57] # numbers on keyboard
            e.returnValue = false # IE hate you
            e.preventDefault();
    
    ) jQuery
    

    You can get compiled Javascript here http://goo.gl/SbyhXN

    0 讨论(0)
提交回复
热议问题