问题
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.
回答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
回答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
回答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.
回答4:
It's not a very good style to include js code into html. Also if there is more than one input you need to avoid code duplicating. So include this to your js file, the other code can be the same
$('.div-with-multiple-inputs').find('input').on('keypress', function() {
return event.charCode >= 48 && event.charCode <= 57;
})
来源:https://stackoverflow.com/questions/27422942/using-charcode-to-allow-only-numbers-and-enter-key