3

I have this input text in a HTML5 page:

<input type="text" class="quantity" 
onkeypress='return (event.charCode >= 48 && event.charCode <= 57) || event.charCode == 8 || event.charCode == 46' required />

Because I need an input text that does allow only numbers, but I could need also delete a number. When I press backspace or delete nothing happens.

The code above only allows numbers. How can I allow also backspace and delete?

VansFannel
  • 43,504
  • 101
  • 342
  • 588

3 Answers3

7

keypress event gives only output of letters code. Use keydown instead.

The keypress event is fired when a key is pressed down and that key normally produces a character value (use input instead).

<input type="text" class="quantity" 
onkeydown='return (event.which >= 48 && event.which <= 57) 
   || event.which == 8 || event.which == 46' required />

I'm using e.which because keydown produce it but, as the doc says, which is deprecated and key should be used instead ( even if not fully implemented )

Check out the Fiddle and keypress docs

steo
  • 4,485
  • 2
  • 32
  • 62
1

this jquery function does it

$('#id').keypress(function(e) {
            var a = [46];
            var k = e.which;
            console.log( k );
                a.push(8);
                a.push(0);

            for (i = 48; i < 58; i++)
                a.push(i);

            if (!($.inArray(k,a)>=0))
                e.preventDefault();
        });
0

You shouldn't use the keypress event, but the keyup or keydown event because the keypress event is intented for real (printable) characters. "keydown" is handled at a lower level so it will capture all non-printing keys like DEL and ENTER

R4nc1d
  • 2,652
  • 1
  • 22
  • 43