Best way to restrict a text field to numbers only?

前端 未结 29 1654
长情又很酷
长情又很酷 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: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

提交回复
热议问题