It’s so simple, but perfect. A great benefit of using the title attribute, is that when you hover over the input, you get a little tooltip displaying the inline label. So all I need to do is add a title attribute with the text that we want to have show up as the inline label. Then, we just use a little jQuery to make it all happen.
The jQuery
First, we want to select each input that has a title attribute, once the document is loaded:
$(document).ready(function() {
$('input[title]').each(function() {
…
});
});
Next, if the value of the input element is empty, we want to take the title attribute and add it as the value of the input.
$(document).ready(function() {
$('input[title]').each(function() {
if($(this).val() === '') {
$(this).val($(this).attr('title'));
}
});
});
After that, we want to setup a function that will fire once the input is focused. When it is focused, if the value is equal to the title attribute, we want to set the value to nothing and add a class of focused:
$(document).ready(function() {
$('input[title]').each(function() {
if($(this).val() === '') {
$(this).val($(this).attr('title'));
}
$(this).focus(function() {
if($(this).val() === $(this).attr('title')) {
$(this).val('').addClass('focused');
}
});
});
});
The reason why we add the class of focused is so that we can change the text color, border or anything to make it noticeable that the input is being focused. You can see this effect in the demo.
Finally, we want to add a function that will fire when the input loses focus. When it does, if the input value is empty, we want to set the value back to the title attribute and remove the class of focused:
$(document).ready(function() {
$('input[title]').each(function() {
if($(this).val() === '') {
$(this).val($(this).attr('title'));
}
$(this).focus(function() {
if($(this).val() === $(this).attr('title')) {
$(this).val('').addClass('focused');
}
});
$(this).blur(function() {
if($(this).val() === '') {
$(this).val($(this).attr('title')).removeClass('focused');
}
});
});
});
And that’s it. It’s just a little bit of code, but it can go a long way. So take it and build on it.
Demo: http://trevordavis.net/play/jquery-inline-form-labels/
Source: http://trevordavis.net/blog/tutorial/jquery-inline-form-labels/

Related Listings:
RSS feed for comments on this post. TrackBack URL
October 24th, 2009 at 6:06 am
[...] jQuery Inline Field Labels [...]
October 26th, 2009 at 5:04 am
[...] jQuery Inline Field Labels [...]