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
  • 45,055
  • 107
  • 359
  • 626

4 Answers4

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,586
  • 2
  • 33
  • 64
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,923
  • 3
  • 24
  • 44
0
$(document).on("keydown",".tel_phone_number",function(evt){
      var ASCIICode = (evt.which) ? evt.which : evt.keyCode;  
      if((ASCIICode > 47 && ASCIICode < 58) || (ASCIICode > 95 && ASCIICode < 106) || jQuery.inArray(ASCIICode, [37,39,8,46]) != -1)
      {
      return true;
      }
      return false;
  })

I have create script for allowed below button in number text box.in this i have allowed backspace , delete , Arrow right,Arrow Left. for backspace code is 8 ,delete code is 46 ,Arrow right is 39 , Arrow Left is 37. if you not allowed delete key then you can remove id [37,39,8,46].this example for remove key.