Computer Magic Logo
Accept only numeric values

Friday, January 22, 2016

Published by Aristotelis Pitaridis

We can use the keydown member function in order to filter the characters that the user types. Below we can see how to allow the user to type only numeric values. We also allow the user the press the backspace and delete keys in order to allow him to delete a character.

$(document).ready(function() {
    $("#txtboxToFilter").keydown(function(event) {
        // Allow backspace and delete
        if ( event.keyCode == 46 || event.keyCode == 8 ) { }
        else {
            if (event.keyCode<48 || event.keyCode > 57 ) {
                event.preventDefault();    
            }    
        }
    });
});