Semantic Inline Form Labels with JQuery

Nov 2, 2009

A very common thing I see in designs I get these days are form labels that are written within the value of their associated input field. This is handy way for designers to save space and make their designs cleaner all-around. Unfortunately for us developers, simply setting the input value isn't very semantic or usable. Thanks to JQuery there's plenty of easy ways to take care of this.


We'll start with the HTML. Nothing fancy here, just your standard form with labels and inputs.

<form id="signup" name="signup">
    <label for="email">Email Address</label>
    <input class="text" name="email" type="text" />
    <label for="zip">Zip Code</label>
    <input class="text zip" name="zip" type="text" />
    <input class="btn" type="submit" value="Sign Up" />

The CSS isn't important at all to what we're trying to accomplish, so I won't cover any of that. The JQuery on the other hand, is what does most of the work. First of all, we will want to loop through our label elements and assign their values to the inputs that immediately follow. Then you'll want to hide those labels. After that, we will handle the focus and blur events to get rid of those values when people click the form input. Here's the JQuery:

The JQuery

$(document).ready(function() {
    $("#signup label").each(function (i) {
    $("#signup input").focus(function() {
        if($(this).prev("label").html()+"..." == this.value){
            this.value = "";
    $("#signup input").blur(function() {
        if(this.value == ""){
            this.value = $(this).prev("label").html()+"...";

Now this is by no means is a new or innovative technique. There are plenty of solutions out there that will accomplish the same goal. This tip is simply what I tend to use to sematically code the designs I get.

Update (12-18-2009): Smashing Magazine recently published an article by Zurb called Stronger, Better, Faster Design with CSS3 that expands on this technique and makes it even better with CSS3 by just masking the label so even when you click into the input you can still read the label.

comments powered by Disqus