HTML text input allow only numeric input

前端 未结 30 3440
孤街浪徒
孤街浪徒 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: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);
    

提交回复
热议问题