2

Possible Duplicate:
How to allow only numeric (0-9) in HTML inputbox using jQuery?

I have a jquery snippet which allows only numbers inside a particular textbox.If the user types a letter/special character, it doesn't allow the character to get into the textbox at all.But it doesn't work.

$("#PostalCode").keydown(function (e) {
            if (e.shiftKey || e.ctrlKey || e.altKey) { // if shift, ctrl or alt keys held down
                e.preventDefault();         // Prevent character input
            } else {
                var n = e.keyCode;
                if (!((n == 8)              // backspace
                        || (n == 46)                // delete
                        || (n >= 35 && n <= 40)     // arrow keys/home/end
                        || (n >= 48 && n <= 57)     // numbers on keyboard
                        || (n >= 96 && n <= 105))   // number on keypad
                        ) {
                    alert("in if");
                    e.preventDefault();     // Prevent character input
                }
            }
        });

The alert message is shown whenever I enter a non-number(letter, or special character), which means that my logic is probably correct. But still the character is displayed inside the textbox, which means that there's something wroing with e.preventDefault(). Can anyone help?

Community
  • 1
  • 1
karan k
  • 947
  • 2
  • 21
  • 45
  • 1
    he's not asking how to do x, he's asking why y isn't working. – Rodik Jul 18 '12 at 13:04
  • @Rodik I don't think so. Where does he ask that? – Esailija Jul 18 '12 at 13:06
  • Esailija, Ben suggested that this is a duplicate of another question, i was pointing out that it wasn't, because this asker already has his own code, and he is asking why e.preventDefault isn't working in his case, he's not asking for a different implementation of his own code. – Rodik Jul 18 '12 at 13:09

2 Answers2

0

According to this Opera preventDefault() on keydown event some browsers dont support preventDefault on keydown. Could this be the case for you?

Maybe you could try on keypress instead?

That or maybe you could use regex and replace invalid characters with ""

Community
  • 1
  • 1
Gaz Winter
  • 2,924
  • 2
  • 25
  • 47
0

Funnily it works, if you have no alert in between, with alert the code breaks.

Christoph
  • 50,121
  • 21
  • 99
  • 128