This input field is useful for entering numerical values (integer or float), but not for entering zip codes. On desktop implementations and on some mobile implementations, it provides a user interface with small vertical arrows for incrementing/decrementing the current value, while on mobiles it will display a numeric keyboard.
For zip codes, a <input type="text" pattern="......"> is preferable. See examples given in the pattern attribute section of this course.
Example: <input type="number" value="25" min="0" step="5" max="500"/>
Screenshot example taken with a mobile device :
Examples on desktop (the width will be adjusted depending on the min and max attributes):
This field accepts specific attributes max, min, step, value (default displayed value).
This input type is very interesting as it provides default validation behaviors:
If the value entered using a keyboard is not a valid number, or is not in the range defined by the min and max attributes, the field is invalid and gets the pseudo CSS class :invalid.
If the difference between the value you enter and min is a multiple of step, then it gets the CSS pseudo class :valid , otherwise it will be invalid. Example: if min=1 and step=5, the field will be valid with value=1, 6, 11, 16 etc. if min=0, with value=0, 5, 10, 15 etc.
Online example in CodePen: (try changing the attribute values, use step="any" and try float values, etc).
Source code:
<!DOCTYPE html>
....
<style>
#number:invalid {
background-color:pink;
}
#number:valid {
background-color:lightGreen;
}
</style>
</head>
<body>
Example of <code><input type=number></code>:<p>
<label for="number">Quantity (between 0 and 500, should be a multiple of 5 otherwise it's invalid): </label>
<input type="number" id="number" value="25" min="0" step="5" max="500"/>
<p>
Change the different values for attributes step, max, min, value. Don't forget to try step="any" for float values...
</body>
</html>