Today we will learn, How To Prevent User From Entering A Non-number In Textbox Using Jquery.
Suppose you have requirement to validate mobile number, if the user types alphabets/special character, it doesn't allow the character to enter in the textbox(it only allow numbers). Also, it allow backspace to delete numbers which you have entered and it also allow to select all(using ctrl+A) and then delete.
Here is HTML code:
<input id="mobNumber" name="mobNmuber" type="text"/>
Here is the JQuery code:
$("#mobNumber").keydown(function (e) {
var id = $(this).attr('id');
$("#"+id).keypress(function(e) {
if ( (e.ctrlKey) || (e.which >= 48 && e.which <= 57) || (e.which == 95) ||
(e.which == 8) || (e.which == 32) || (e.which == 0)) {
}
else
{
e.preventDefault();
}
});
});
Check running example here: http://jsfiddle.net/jeetu_verma11/kLP2n/
0 comments:
Post a Comment