Accept only numbers from user using javascript No ratings yet.

By | May 24, 2016

Among all browser few browsers use keyCode, others use which. If you’re using jQuery, you can reliably use which.
Method 1:
The below JavaScript code can be used to validate user input to accept only numbers:

 

if (charCode > 31 && (charCode < 48 || charCode > 57)):

This checks that the key pressed is numerical(It is checking that the keyCode is between 48 and 57).
It will evaluate to true for any character that is not a number.
This code should be effective on all type of keyboards. the script checks whether the pressed key(input character) is numeric or not.
i.e. ASCII value not between 31 and 48 also not greater than 57(i.e. between 48 and 57), which are numbers. This is done as soon as the user press the key, the Key code is identified.
Method 2:

The below JavaScript code can be used to validate user input to accept numbers with one decimal values.

 

Method 3: Using regular expression

The below JavaScript code can be used to validate user input to accept numbers with one decimal values.

Method 4: Using HTML 5 attribute: Using HTML5 attribure you can do it like this:

This does not require JavaScript. But remember this does not work in many modern browser.

Method 5:

The most reliable way is to use this:

 

 

 

Likes(0)Dislikes(0)

Please rate this

Leave a Reply

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