18

I want to prevent number input on keydown event on textfield and run custom handler function. Here are the issues

  • e.target.value is useless since the key value is not projected into the target value yet
  • e.keyCode for number depends on keyboard type, language layout, Fn or Shift key
  • String.fromCharCode(e.keyCode) is not reliable, at least on my keyboard (Czech qwerty)
  • w3 specification says e.keyCode is a legacy attribute and suggests e.char instead, but it is not implemented in browsers yet

So how to catch the number input before it appears in the textfield?

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169

4 Answers4

30

Use the keypress event instead. It's the only key event which will give you information about the character that was typed, via the which property in most browsers and (confusingly) the keyCode property in IE. Using that, you can conditionally suppress the keypress event based on the character typed. However, this will not help you prevent the user from pasting or dragging in text containing numeric characters, so you will still need some kind of extra validation.

My favourite reference for JavaScript key events: http://unixpapa.com/js/key.html

textBox.onkeypress = function(e) {
    e = e || window.event;
    var charCode = (typeof e.which == "undefined") ? e.keyCode : e.which;
    var charStr = String.fromCharCode(charCode);
    if (/\d/.test(charStr)) {
        return false;
    }
};
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Unbelievable! Sometimes is the `e.keyCode` different in `keypress` and `keydown` event! At least in my latest Chrome. Is it a feature or bug? – Jan Turoň Mar 31 '13 at 14:13
  • @JanTuroň: According to http://unixpapa.com/js/key.html, in WebKit `keyCode` is the same as `which` in `keypress` events, which could easily be different from the `keyCode` in a `keydown` event (think upper and lower case letters, for a start: same key code, different character codes). – Tim Down Mar 31 '13 at 14:28
  • @JanTuroň: Your edit was wrong, by the way, so I rolled it back. You only need to use `e.returnValue` in old IE, and even then not in DOM0 handlers like the one in my example. – Tim Down Mar 31 '13 at 14:31
16

Try this to replace integer values:

<input onkeydown="Check(this);" onkeyup="Check(this);"/>

<script>
function Check(me) {
    me.value = me.value.replace(/[0-9]/g, "");
}
</script>

To prevent integer input:

<input onkeydown="Check(event);" onkeyup="Check(event);"/>

<script>
function Check(e) {
    var keyCode = (e.keyCode ? e.keyCode : e.which);
    if (keyCode > 47 && keyCode < 58) {
        e.preventDefault();
    }
}
</script>
palaѕн
  • 72,112
  • 17
  • 116
  • 136
  • Partially, see the second and third bullet in my question: number input on numeric part of keyboard ranges from 96 to 105, it doesn't return number on `String.fromCharCode` and it may also vary depending on keyboard layout and switching keys. – Jan Turoň Mar 31 '13 at 11:14
1

One-line solution

$('#input-field').keydown(e => !String.fromCharCode(e.which).match(/\d/g))
Raofin
  • 31
  • 1
  • 4
  • 1
    I got `Uncaught ReferenceError: $ is not defined` - is it some kind of obsolete library you suggest to use for such a simple task? – Jan Turoň Sep 03 '22 at 18:31
  • `$` coming from the jQuery library. I think almost everyone uses it :) – Raofin Sep 03 '22 at 19:44
  • 1
    It was true in 2010, but [not anymore](https://www.google.com/search?client=opera&q=should+i+use+jquery). – Jan Turoň Sep 04 '22 at 17:24
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 08 '22 at 07:05
0

My solution to prevent floating code characters

    // 'left arrow', 'up arrow', 'right arrow', 'down arrow',
    const = arrowsKeyCodes: [37, 38, 39, 40],
    // 'numpad 0', 'numpad 1',  'numpad 2', 'numpad 3', 'numpad 4', 'numpad 5', 'numpad 6', 'numpad 7', 'numpad 8', 'numpad 9'
    const = numPadNumberKeyCodes: [96, 97, 98, 99, 100, 101, 102, 103, 104, 105],

    export const preventFloatingPointNumber = e => {
    // allow only [0-9] number, numpad number, arrow,  BackSpace, Tab
    if ((e.keyCode < 48 && !arrowsKeyCodes.includes(e.keyCode) || e.keyCode > 57 &&
        !numPadNumberKeyCodes.includes(e.keyCode)) &&
        !(e.keyCode === 8 || e.keyCode === 9))
        e.preventDefault()
    }
Palaniichuk Dmytro
  • 2,943
  • 12
  • 36
  • 66