Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  151] [ 7]  / answers: 1 / hits: 15299  / 9 Years ago, mon, april 20, 2015, 12:00:00

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?


More From » jquery

 Answers
12

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


[#66994] Saturday, April 18, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
arthur

Total Points: 729
Total Questions: 107
Total Answers: 109

Location: China
Member since Mon, Aug 22, 2022
2 Years ago
;