Input Prompt Text: A Better Way
It’s a very cool feature to have a form field that has prompt text such as Enter search keywords… right inside the input box, itself. It looks good, it makes sense to users, and it can save a lot of real estate in your design by negating the need for field labels. The problem, however, is that there are about one hundred ways to implement prompt text, and ninety-nine of them are wrong. Let’s look at this thing from all angles and come up with a fantastically simple and reliable way to make this work.
What is input prompt text?
You’re probably familiar with the concept, even if you don’t know what I’m talking about. Here’s an example:
The prompt text appears inside the form field as soon as the page loads, so users immediately know what it’s for. Simple, right?
Why it Doesn’t Work
There are a number of problems you’ll encounter while implementing prompt text into your forms. Watch out for these caveats when you’re developing your own solution.
- Input validation — if someone submits the form without first removing the prompt text, your prompt text is submitted in lieu of real data. Fixing this is a pain. Avoiding this entirely is recommended.
Almost everything related to the problems listed above originates from one basic fact: you’re trying to create both a field and a label using a single HTML element. When you take a step back and think about that, it really doesn’t make much sense, does it? The solution lies in separating the form field from the label entirely. We’ll use a little bit of jQuery to create an elegant solution that dynamically creates these labels and places them over our form fields. Because we’re creating two separate elements, we can use CSS to style them independently. Perfect!
Basically, this script finds any
<input> tags that have a
title attribute (i.e.
<input title="Enter search keywords..." />). For each of these form fields, it takes the
title and creates a little
<span> tag next to it. The CSS positions the
<span> tag so that it appears on top of the form field. The rest is just a little bit of scripting that makes sure to hide and show the labels based on what the user is doing with the input box.
Here is a demo of the code shown above:
margin a bit in the CSS to make sure the labels fit the size of your input boxes. For more information on jQuery and all the great things it can do, visit jQuery.com.