0

I'm trying to restrict my text field for numbers only. I'm using:

onkeypress="return (event.charCode >= 48 && event.charCode <= 57)"

The troubles appears when I want delete (using backspace o delete key) or move my cursor in another position using arrow keys, cause I can't use these keys.

So now, I have this code:

onkeypress="return ((event.charCode >= 48 && event.charCode <= 57) || event.charCode == 8)"

It is an example, charCode == 8 is for allow backspace. It doesn't work in Firefox. I'm still restricting text field to numbers, but I still can't use my backspace key.

Can you give me a hand? Do you know what are I'm doing wrong?

Keycode: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

eugneio dsjgfo
  • 121
  • 1
  • 4

1 Answers1

2

Use event.which

<input onkeypress="return ((event.which >= 48 && event.which <= 57) || event.which == 8)">

Alternatively you could use event.key and use actual key names to test for validity.

function handleNumericEditable(event){
  var allowed = /^[0-9]|Arrow(Left|Right)|Backspace|Home|End|Delete$/
  return allowed.test(event.key);
}
<input onkeypress="return handleNumericEditable(event)">
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317