Numbers As Spinboxes

Next up: numbers. Asking for a number is, in many ways, trickier than asking for an email or web address. First of all, numbers are more complicated than you might think. Quick: pick a number. –1? No, I meant a number between 1 and 10. 7½? No, no, not a fraction, silly. π? Now you’re just being irrational.

My point is, you don’t often ask for “just a number.” It’s more likely that you’ll ask for a number in a particular range, and you may only want certain kinds of numbers within that range—maybe whole numbers but not fractions or decimals, or something more esoteric like numbers divisible by 10. HTML5 has you covered. Let’s look at an example:

<input type="number"
       min="0"
       max="10"
       step="2"
       value="6">

Let’s take that one attribute at a time (you can follow along with a live example if you like):

  • type="number" means that this is a number field.

  • min="0" specifies the minimum acceptable value for this field.

  • max="10" is the maximum acceptable value.

  • step="2", combined with the min value, defines the acceptable numbers in the range: 0, 2, 4, and so on, up to the max value.

  • value="6" is the default value. This should look familiar. It’s the same attribute name you’ve always used to specify values for form fields. (I mention it here to drive home the point that HTML5 builds on previous versions of HTML. You don’t need to relearn how to do stuff you’re already doing.)

That’s the markup side of a number field. Keep in mind that all of those attributes ...

Get HTML5: Up and Running now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.