3

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?

3
  • 1
    he's not asking how to do x, he's asking why y isn't working. Commented Jul 18, 2012 at 13:04
  • @Rodik I don't think so. Where does he ask that? Commented Jul 18, 2012 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. Commented Jul 18, 2012 at 13:09

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

1 Comment

:O Never noticed that! Thanks
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 ""

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.