Few days back, my friend Parleen asked me how can we
make a textbox which just accepts only numbers specially digits only.
And, for his I come up with this solution of textbox which only accepts
digits, and if you try to enter any alpha bates in it then it displays
the error message with animation.

View Demo

HTML Code

As you can see above, I’ve given the name and id of
textbox to “quantity” in this example.This is the textbox which only
accepts numbers (digits only). You can see “span” after textbox which
is used to display the error message with fading effect using jQuery.

Javascript Code

First of all, we need to use jQuery library as we’re using the jquery’s function to accept only digits.

Now le’ts write the code in JavaScript using jQuery to accept only digits in textbox and displaying error with animation.

When the key is pressed, we’re using the key’s ASCII
value to check which button is pressed. In first expression, delete,
tab or backspace button is is checked and “8″ is the ASCII values of
the Back-space. Digits are checked in the second expression. “48″ is
the ASCII values of “0″ and “57″ is the ASCII values of “9″. The the
ASCII values of the other digits lies between “48″ to “57″. And, if the
key pressed values doesn’t lies withing these range, then we are
displaying the error message with jQuery’s fading effect.

And, the “return false” statement means that this
functions returns false values which means not to type anything on the
text box.

Download Full Source Code

Leave a Reply

电子邮件地址不会被公开。 必填项已用*标注