JavaScript: Allow only numeric key presses.

Posted February 2nd, 2013


The following code allows only numeric characters to be entered.

<html>
<head>
<script type="text/javascript">
    function checkIt(evt) {
        evt = (evt) ? evt : window.event
        var charCode = (evt.which) ? evt.which : evt.keyCode
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            document.getElementById("errorMessage").innerHTML = "This field accepts numbers only."
            return false
        }
        document.getElementById("errorMessage").innerHTML = ""
        return true
    }
</script>
</head>
<body>
    <input id="numbersOnly" type="text" onKeyPress="return checkIt(event)" />
    <span id="errorMessage"></span>
</body>
</html>