0

I Have this JavaScript code to allow only numeric input on textboxes

    function CheckNumeric(e) {

        if (window.event) // IE 
        {
            if ((e.keyCode < 48 || e.keyCode > 57) & e.keyCode != 8) {
                event.returnValue = false;
                return false;
            }
        }
        else { // Fire Fox
            if ((e.which < 48 || e.which > 57) & e.which != 8) {
                e.preventDefault();
                return false;
            }
        }
    }

The problem is that it's also preventing the "TAB" button! which I like to allow.

How can I do that?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Soufiaane
  • 1,737
  • 6
  • 24
  • 45

3 Answers3

2

I would change the CheckNumeric function into something like this and use a regex to determine valid/invalid input. /[0-9\t\b]+/ matches numbers, tabs and backspace. if you also want to allow space change it to /[0-9\t\b\s]+/

function CheckNumeric(e)
{
    var charCode = e.charCode || e.keyCode;
    var character = String.fromCharCode(charCode);
    if(!character.match(/[0-9\t\b]+/))
    {
        if(window.event)
            event.returnValue = false;
        else
            e.preventDefault();
        return false;
    }
    return true;
}

additionally, in order to capture keycodes correctly you should bind to the onKeyPress event instead of onKeyDown as it will not provide correct keycodes for the numeric keypad.

<input type="text" onkeypress="CheckNumeric(event)"/>
Christian Westman
  • 2,985
  • 1
  • 26
  • 28
0

KeyCode 8 is for backspace. I dont know if you added by mistake or not:

function CheckNumeric(e) {

    if (window.event) // IE 
    {
        if ((e.keyCode < 48 || e.keyCode > 57) & e.keyCode != 8 & e.keyCode != 9) {
            event.returnValue = false;
            return false;
        }
    }
    else { // Fire Fox
        if ((e.which < 48 || e.which > 57) & e.which != 8  & e.which != 9) {
            e.preventDefault();
            return false;
        }
    }
}
Anujith
  • 9,370
  • 6
  • 33
  • 48
0

The approach I prefer using here (cleaner code, simpler logic) is to use an html5 attribute (either type="number" or pattern="[0-9]*" would work well).

See Disable webkit's spin buttons on input type="number"? if you decide to use <input type="number"> and want to disable the spinners.

If you really need to support older browsers with this behavior, consider using a shim that supports html5 form attributes.

Community
  • 1
  • 1
Ben Taitelbaum
  • 7,343
  • 3
  • 25
  • 45