I want to input only numbers in HTML or Javascript. What are different ways for this? Thanks.
Printable View
I want to input only numbers in HTML or Javascript. What are different ways for this? Thanks.
You've got the HTML <input> tag type of "number" which is the easiest.
https://www.w3schools.com/html/html_...nput_types.asp
If you're using jQuery you can add to jQuery a plug-in which handles this when a key is pressed:
And then you can use <input> with type "text" and apply a class to it, e.g. "NumbersOnly" which in turn calls this:Code:jQuery.fn.forceNumeric = function () {
return this.each(function () {
$(this).keydown(function (e) {
var key = e.which || e.keyCode;
if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
key >= 48 && key <= 57 || key >= 96 && key <= 105 || key == 8 || key == 9 || key == 13 ||
key == 35 || key == 36 || key == 37 || key == 39 || key == 46 || key == 45)
return true;
return false;
});
});
}
This blocks users from typing anything other than numbers however it does prevent them from pasting anything in regardless of whether that's a number.Code:$('input[type=text].NumbersOnly').forceNumeric();
There are lots of ways to do this:
http://letmegooglethat.com/?q=only+a...ml+input+field