Html Page:
<input type="text" name="age" id="txtAge" /> <span id="errormsg"></span>
JQuery Snippet for the above TextBox:
Method-1:
$(document).ready(function () {
//called when key is pressed in textbox
$("#txtAge").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errormsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
Method-2:
$(document).ready(function () {
$("#txtAge").keydown(function (e) {
if (e.shiftKey) e.preventDefault();
else {
var nKeyCode = e.keyCode;
//Ignore Backspace (Keycode=8), Tab keys(Keycode=9) & Delete(Keycode=46)
if (nKeyCode == 8 || nKeyCode == 9 || nKeyCode == 46) return;
if (nKeyCode < 95) {
if (nKeyCode < 48 || nKeyCode > 57) e.preventDefault();
} else {
if (nKeyCode < 96 || nKeyCode > 105) e.preventDefault();
}
}
});
});
Enjoy!
No comments:
Post a Comment