When it comes to forms, one thing I hear a lot about is setting them up using PHP; HTML has basic form capability, but don’t you want them to do more?
With HTML5, forms can indeed do more, without the need for any fancy scripting. The best part is, all of the new features degrade gracefully, which means you can use them now without spending a lot of time worrying about what they’ll do in legacy browsers.
Let’s start with the basic elements of an HTML form, which are the same in HTML 4 and 5:
<input name=”name” type=”type” value=”value”>
That’s all there is to it! Let’s take a look at each of these elements. The name tag identifies the input, which lets you refer to it later; this is particularly important when you’re using it to pass information to the next page. The type tag tells the browser what type of input to use, such as a button or dropdown. Finally, the value field is the default value; for a button, this would be the displayed text. Each of these tags is optional.
The nice thing is that when a browser doesn’t understand the given type, or the type is not given, it simply displays it as a text field rather than giving unpredictable behavior. This means we can use new HTML5 input types, knowing that people with older browsers will still have a way to provide input.
How about an example? Suppose I want you to choose an even number between 8 and 22, with a default of 12. I can do that using the following code:
<form> <input type=”number” min=”8″ max=”22″ step=”2″ value=”12″> </form>
If you’re using an HTML5-compliant browser such as Opera, the following should show up as a spinbox that allows only the even numbers between 8 and 18. In older browsers, it will show as a simple text field, but will still be validated – the form will refuse to submit if the user enters an illegal value. The second field is the same code with the type changed to range.
So why use these special tags instead of just having the user type a number? For one thing, it can be optimized in various ways. If you’re viewing this page on an iPhone, you won’t get a spinbox, but your keyboard will default to numbers. A search field (another new type) may be functionally the same as a text box, but if you’re using Safari on a mac, it’ll have rounded corners to look like the standard mac search boxes; on both Safari and Chrome, once you start typing a little x will appear to erase the field. While browsers don’t handle these tags in the same way, telling them what type of data is expected allows the more appropriate data entry.
<form> <input name=”tellme” autofocus placeholder=”Placeholder Text”> </form>
Depending on which browser you’re using, both, one, or none of the new attributes we’re using will take effect; whichever ones don’t will simply be ignored. Autofocus (predictably) sets the focus to this field, while placeholder text appears in light grey to tell you what you’re supposed to type: