Html Text Input Allow Only Numeric Input – POFTUT

Html Text Input Allow Only Numeric Input

Applications expecting numeric values for the input is generally a pain for developers. Because we have to check given values whether they are number or alphabet. We have some text input element for html. We want to get the number of the person. How can we achieve that easily?

Pure JavaScript

By using JavaScript events is the most reliable method. We will write some JavaScript for onkeypress event and check the key code. This is a simple code where we check the entered values ASCII codes and if they are inside the number range we return them.

<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
  • onkeypress is the event will be triggered
  • return will return code if the code is number which is between 48 and 57


Html5 provides native tag which can only accept numeric input. We can use input tag with the number type which will accept only decimal numbers.

<input type="number">

At least keep in mind that to make things more secure server side filtering is a must. Do not values provided by the client side.

LEARN MORE  How To Pause and Resume Powershell and Cmd Scripts In Windows With Examples?

Leave a Comment