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?
Funnily it works, if you have no alert in between, with alert the code breaks.