-
July 26th, 2019, 04:17 AM
#1
Input Only Numbers with HTML
I want to input only numbers in HTML or Javascript. What are different ways for this? Thanks.
-
July 31st, 2019, 11:18 AM
#2
Re: Input Only Numbers with HTML
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:
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;
});
});
}
And then you can use <input> with type "text" and apply a class to it, e.g. "NumbersOnly" which in turn calls this:
Code:
$('input[type=text].NumbersOnly').forceNumeric();
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.
There are lots of ways to do this:
http://letmegooglethat.com/?q=only+a...ml+input+field
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|