How to force Input field to enter only numbers using JavaScript

How to force Input field to enter numbers only using JavaScript

Share Now:

Share on facebook
Share on linkedin
Share on twitter
Share on email

HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery.

The following examples will explain how to force input field force numbers.

  • By using ASCII code
  • By using replace(), isNan() function

Definition and Usage

The <input type="number"> defines a field for entering a number.

Use the following attributes to specify restrictions:

  • max – specifies the maximum value allowed
  • min – specifies the minimum value allowed
  • step – specifies the legal number intervals
  • value – Specifies the default value

Tip: Always add the <label> tag for best accessibility practices!

Example below illustrate Input[type=”text”] allow only Numeric Value using Javascript with the help of ASCII code.

<!DOCTYPE html>
<html lang="en">
	<meta charset="utf-8">
	<meta name="viewport"
		content="width=device-width, initial-scale=1">
		div {
			width: 400px;
			height: 130px;
			border: 2px solid black;
			padding: 15px;
			position: absolute;
			left: 27%;
		<h1 style="color:green;padding:13px;">
		Interset Form Validation
		Force input field to take only numbers as an input
	<div class="container">
		<form name="inputnumber"
			<b>Register No:</b>
			<input type="text"
				onkeypress="return onlyNumberKey(event)"
				size="50%" />
			<b>Ph. Number:</b>
			<input type="tel"
				onkeypress="return onlyNumberKey(event)" />
				<input type="number"
					placeholder=" Only 12+ allowed"
					min="12" />
				<input type="submit"
					onclick="return detailssubmit()">
	function onlyNumberKey(evt) {
		// Only ASCII character in that range allowed
		var ASCIICode = (evt.which) ? evt.which : evt.keyCode
		if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))
			return false;
		return true;
	function detailssubmit() {
		alert("Your details were Submitted");

Get Free Access to InterSet’s 1 GB SSD Hosting with Website Design

Know Your Entity Destiny Offers Savings

More You Would be interested in . . .

Have you any Question ?
Ask us !