Signup/Sign In
PUBLISHED ON: JULY 29, 2021

How to create an input field that takes numbers as its input?

Answer: Using input tag with type attribute having value number

The input field with only numbers is widely used in the webpages. Some input field like adding any phone number, age or Pincode requires only the number. So HTML provides an input field that can be used to enter numbers.

Create an input field that takes on the number in HTML

The input field can be created using the <input> tag. Add type="number" to the <input> so that it can only take numbers as input. It will automatically validate and does not accept non-numerical numbers. All the modern days' browsers support the number input field. But if somehow the browser does not support it then the input field changes to type="text".

Example: Create an input field of type number

Here in the example, we have created an input field that takes only the number.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
</head>
<body>
    <h2> Input field for number</h2>
	<label for="num"> Enter number </label>
    <input type="number" id="num" name="num">
</body>
</html>

Output:

HTML Number Input field

Attributes used in the input field

There is a list of attributes used in the input field for numbers.

  • value - The value attribute is used to add the default number to the input field.

  • max - The maximum value accepted by the input field is defined by this attribute.

  • min - The minimum value accepted by the input field is defined using the min attribute.

  • step - The input field has an up-down arrow to adjust the value. The step attribute can be used to set the interval to step up or down.

Example: Using attributes in the input field

Here in the program, we have set the limit of the number by setting max and min values. Further, the step value is set to 1.

Conclusion

The number input field has great usability. It does not accept the wrong input type from the users which saves the time for validating in the later phase. It is user-friendly and provides max and min values if we want to limit the number value. HTML provides an easy and simple way to add the number input field.



About the author: