Allow only numeric values or digits in a TextBox using JavaScript or jQuery

This tutorial shows how to accept only numbers or digits in a textbox using JavaScript or jQuery. Sometimes we need to accept only numbers for a textbox instead of validation then it comes handy. In this type of validation user will not be able to type a non-numeric values. This tutorial shows both validation and accepting only numbers in a textbox. This example also shows inline JavaScript function call with the input textbox. We will see each example one by one.

Example One – using JavaScript

The javascript function checks for charcode when a key is pressed in the keyboard and it check if it does not fall between 48 and 57 then it is other than digit. So we show the error message to the user. We call the javascript function onkeypress javascript event. You can also call this function onkeyup javascript function.

For more information on charcode or keycode please go through http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

 

Example Two – using jQuery

Below example uses jQuery to check and replace the non-digit values. The below jQuery function is fired on the keyup event

 

The function here just test for the digits and if the value is not a digit then it just replaces that value.

The below logic tells if user presses the Delete (keyCode – 46) or Backspace (keyCode – 8), then do nothing

 

Source Code

 

Example Three – Inline JavaScript

In this below example we have input textbox and onkeyup javascript event we have written inline logics. So we don’t have any external function attached to this onkeyup event. The logic inside the onkeyup event just test the input value and if it is not digit then just replaces that value.

 

Putting all together

 

Final output

allow only numbers or digits using jquery or javascript

That’s all. Thanks for your reading. Please do not forget to leave a comment.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.