KP Joy KP Joy - 1 month ago 9
HTML Question

HTML Text containing numbers only

I have a textbox which should accept numbers only as this text is for roll number. My following code is serving my purpose.

<html>
<head><title>Sample Webpage</title></head>
<body>
<input type="text" name="roll_number" id="roll_number" value="25" placeholder="roll number" autocomplete="off" tabindex="1" maxlength="3" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
</body>
</html>


But I am encountering a problem in Firefox. When I try to delete the roll number by using BACKSPACE/DELETE nothing is working. Its also not accepting these keys. But this is working fine in Chrome and IE. What should be the fix?

Answer

A fast solution is to check also if the pressed key is "Backspace", so you can modify your code with this:

<input type="text" name="roll_number" id="roll_number" value="25" placeholder="roll number" autocomplete="off" tabindex="1" maxlength="3" onkeypress='return (event.charCode >= 48 && event.charCode <= 57) || event.keyCode == 8'>