= 48 && event.charCode <= 57"> I use it on inputs to allow only numbers. But now i need " /> = 48 && event.charCode <= 57"> I use it on inputs to allow only numbers. But now i need " /> = 48 && event.charCode <= 57"> I use it on inputs to allow only numbers. But now i need "/>

Using charcode to allow only numbers and enter key

17.6k Views Asked by At

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.

5

There are 5 best solutions below

1
Petru Lebada On BEST ANSWER

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

0
Boon Hock Teh On

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

0
Fedor On

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;
    })
1
Carolyn Bump On

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.

0
Brandonjgs On

This works for me, allow only numbers 0-9 and .

onkeypress="return event.charCode >= 46 && event.charCode <= 57"