Using charcode to allow only numbers and enter key
Solution 1
you can try:
onkeypress="return event.charCode >= 8 && event.charCode <= 57"
In this way you can allow enter key,numbers..and few other characters,except for alphabetic characters.I don't see any other way. Source: click
Solution 2
You might try:
onkeypress="return (event.charCode >= 48 && event.charCode <= 57) || event.charCode == 13"
event.charCode >= 48 && event.charCode <= 57
is for numbers 0-9
event.charCode == 13
is for enter
Solution 3
If you do something like:
onkeypress="return event.charCode >= 8 && event.charCode <= 57"
and you want the user to be able to delete or backspace make sure you include:
onkeypress='return event.charCode >= 48 && event.charCode <= 57 || event.keyCode == 8 || event.keyCode == 46'
The keycodes to 8 and 46 are the delete and backspace. The first solution only works completely in chrome.
Comments
-
Petru Lebada almost 2 years
I have this syntax:
<input onkeypress="return event.charCode >= 48 && event.charCode <= 57">
I use it on inputs to allow only numbers. But now i need to allow the enter key too since i can no longer use a button to submit the form(personal reasons).By now i found this:
event.charCode = 13 // allows enter key
but i can't seem to find how to build the onkeypress syntax.Any help ? Thank you.
-
Gopakumar N G over 6 yearsHow to allow only numbers and one decimal point values. For example allowing the user to input values like 0.5,1,1.5,2,2.5 and not 0.33,1.265,2.12
-
Kym NT almost 2 yearswhat should I include for dash -