How to avoid Decimal values in input type number

How to avoid Decimal values from input of Number in HTML5. Currently it allows user to type decimal value.


Solution 1:

An alternative to the supplied answers is to monitor the keypress while in the input. I personally like leaving the type="number" as an attribute. Here's a JSFiddle

<form action="#" method="post">
  Numbers: <input name="num" 
                  type="number"
                  min="1"
                  step="1"
                  onkeypress="return event.charCode >= 48 && event.charCode <= 57"
                  title="Numbers only">
  <input type="submit">
</form>

Solution 2:

I ended up checking to see if a user types in a period then preventing the event from propagating.

Edit: A better approach. The key press event has been deprecated. Also added in a regex to strip out everything but numbers [0-9] on paste.

<input type="number" onkeydown="if(event.key==='.'){event.preventDefault();}"  oninput="event.target.value = event.target.value.replace(/[^0-9]*/g,'');">

Caution Experimental. Only partially works on chrome: Wanted to look at a great way to grab the pasted value strip everything out then have it placed in input as normal. With the above method you are relying on the event order to correct the input, then any event listeners will ideally fire after. The onpaste method will fire before the input event fires so you keep the flow of events correct. However when replacing the string with only numbers the decimal point would still sneak in. Looking to update this when I find a better solution.

<input type="number" onkeydown="if(event.key==='.'){event.preventDefault();}" onpaste="let pasteData = event.clipboardData.getData('text'); if(pasteData){pasteData.replace(/[^0-9]*/g,'');} " >