I need to make sure that a certain <input> field only takes numbers as value.
The input is not part of a form. Hence it doesn’t get submitted, so validating during submission is not an option. I want the user to be unable to type in any characters other than numbers.
Is there a neat way to achieve this?
HTML 5
You can use HTML5 input type number to restrict only number entries:
This will work only in HTML5 complaint browser. Make sure your html document’s doctype is:
<!DOCTYPE html>See also https://github.com/jonstipe/number-polyfill for transparent support in older browsers.
JavaScript
Update: There is a new and very simple solution for this:
See this answer or try it yourself on JSFiddle.
For general purposes, you can have JS validation as below:
If you want to allow decimals replace the if-conditio" with this:
Source: HTML text input allow only numeric input