Here’s a cute little markup pattern for ya.
Suppose you’ve got an input element that has—by means of a list attribute—an associated datalist. Here’s the example I used in HTML5 For Web Designers:
<label for="homeworld">Your home planet</label>
<input type="text" name="homeworld" id="homeworld" list="planets">
<datalist id="planets">
<option value="Mercury">
<option value="Venus">
<option value="Earth">
<option value="Mars">
<option value="Jupiter">
<option value="Saturn">
<option value="Uranus">
<option value="Neptune">
</datalist>
That results in a combo-box control in supporting browsers: as you type in the text field, you are presented with a subset of the options in the datalist that match what you are typing. It’s more powerful than a regular select, because you aren’t limited by the list of options: you’re free to type something that isn’t in the list (like, say, “Pluto”).
I’ve already written about the design of datalist and how you can use a combination of select and input using the same markup to be backward-compatible. I like datalist.
I also like the placeholder attribute. Another recent addition to HTML, this allows you to show an example of the kind of content you’d like the user to enter (note: this is not the same as a label).
It struck me recently that all the options in a datalist are perfectly good candidates for placeholder text. In the example above, I could update the input element to include:
<input type="text" name="homeworld" id="homeworld" list="planets" placeholder="Mars">
or:
<input type="text" name="homeworld" id="homeworld" list="planets" placeholder="Saturn">
I wrote a little piece of JavaScript to do this:
- Loop through all the
inputelements that have alistattribute. - Find the corresponding
datalistelement (its ID will match thelistattribute). - Pick a random
optionelement from thatdatalist. - Set the
placeholdervalue of theinputto thatoptionvalue.
Put that JavaScript at the end of your document (or link to it from the end of your document) and you’re all set. You might want to tweak it a little: I find it helps to preface placeholder values with “e.g.” to make it clear that this is an example value. You can do that by changing the last line of the script:
input.setAttribute('placeholder','e.g. '+value);
You also might want to show more than one possible value. You might want the placeholder value to read “e.g. Mercury, Venus, Earth, etc.” …I’ll leave that as an exercise for the reader.