How to prevent number input in JavaScript/JQuery

This tutorial demonstrates how to prevent number input on a textfield using JavaScript/JQuery. This example prevents number input from the numpad and the numbers above the keyboard.

  1. Prevent number input using plain javascript, with the keydown and keyup event listeners.
  2. Prevent number input using JQuery, with the keypress event listener.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Prevent Number Input</title>
</head>
<body>

    <form>

        <h1>Prevent Number Input JavaScript</h1>
        <input type="text"
               onkeydown="preventNumberInput(event)"
               onkeyup="preventNumberInput(event)">

        <h1>Prevent Number Input JQuery</h1>
        <input type="text" id="text_field"/>

    </form>

    <script src="jquery.min.js"></script>
    <script src="script.js"></script>

</body>
</html>

The script.js is located in the same directory as the html page.

function preventNumberInput(e){
    var keyCode = (e.keyCode ? e.keyCode : e.which);
    if (keyCode > 47 && keyCode < 58 || keyCode > 95 && keyCode < 107 ){
        e.preventDefault();
    }
}

$(document).ready(function(){
    $('#text_field').keypress(function(e) {
        preventNumberInput(e);
    });
})
  • The keycodes from 48 to 57 are for numbers on the keyboard.
  • The keycodes from 96 to 105 are for numbers on the numpad.

Demo



Download

References

You may also like...