Allow Only Numbers In a Text Box Using JQuery

In some occasions you might have to disable alphabets in a text field and only allow numbers. For example, in fields like phone number or amount.

You can achieve this using the JQuery code given below:


//ALLOW ONLY NUMBERS
$("#mobilenumber").keydown(function(event) {
// Allow: backspace, delete, tab, escape, enter and
if ( $.inArray(event.keyCode,[46,8,9,27,13]) !== -1 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.keyCode == 67 && event.keyCode == 86 || event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
return;
}
else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
});
//END OF ALLOWING ONLY NUMBERS

Advertisements

One thought on “Allow Only Numbers In a Text Box Using JQuery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s