HTML input for Positive Whole Numbers Only (Type=number)

To allow only number values you can use as follows:

<td><input type="number" pattern="\d+" name="itemConsumption" /></td>

You can use type, min and oninput

<input type="number" min="0" step="1" oninput="validity.valid||(value='');">

<form>
<label>Input with positive numbers only</label><br/><br/>
<input type="number" min="0" step="1" oninput="validity.valid||(value='');">
</form>

I tried a lot of different solutions to achieve this, and I finally came up with this one, which does the job perfectly for us. It works for typing and for copy/paste, and I couldn't find any unwanted side-effects.

<form>
    <input
        type="number"
        min="0"
        step="1"
        onfocus="this.previousValue = this.value"
        onkeydown="this.previousValue = this.value"
        oninput="validity.valid || (value = this.previousValue)"
    />
</form>

It is like Nikhil Mahirrao's solution, but it will cause invalid keystrokes to be simply ignored without emptying the input.


To disallow any input but numeric, you may use

<input type="text" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" name="itemConsumption" />
                   ^------------....

<form id="mfrm">
<table>
    <tr>
        <td>Enter number only: <input type="text" name="itemConsumption" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" /></td>
        <td><input type="Submit"/></td>
    </tr>
</table>

Here, the event.charCode == 8 || event.charCode == 0 || event.charCode == 13 condition handles the case when DELETE, BACKSPACE or ENTER keys are pressed (important for Firefox, see Mohit's comment below and datashaman's comment related to enabling the ENTER key).

The event.charCode >= 48 && event.charCode <= 57 means that only 0 (decimal code 48) and all other digits up to 9 (decimal code 57) will be returned.