Tuesday, April 29, 2014

Integer-Only Textbox in jQuery

I often have the need to only allow certain inputs in a textbox.  This is an example of how to limit the users' input to only numbers, backspace, delete, tab, and the arrow keys.  All other keys will be interrupted by a preventDefault() call that stops their default action from executing.  Bind this to the keypress or keydown event (you can also use keyup, but I don't like the way that works).

$("off", "keydown");
$("on", "keydown", function(e) {
    if (e.shiftKey) {
        e.preventDefault();
    } else {
        var nKeyCode = e.keyCode;
        //Ignore Backspace, Delete and Tab keys
        if (nKeyCode == 8 ||
            nKeyCode == 9 ||
            nKeyCode == 46 ||
            (e.keyCode >= 37 && e.keyCode <= 40)) {
            return;
        }
        if (nKeyCode < 95) {
            if (nKeyCode < 48 || nKeyCode > 57) {
                e.preventDefault();
            }
        } else {
            if (nKeyCode < 96 || nKeyCode > 105) {
                e.preventDefault();
            }
        }
    }
});

No comments:

Post a Comment