How to prevent number input on keydown?

十年热恋 提交于 2019-11-28 07:38:42

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;
    }
};

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>

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()
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!