I’ve been seeing the trend of applying inline labels on form elements more and more these days. So I definitely needed to come up with a solid solution that would help me easily apply this effect.
Maybe I need to explain a little better what I am referring to. Instead of using a label that is next to or above the input element, the label is actually within the input. Then, when the input is focused, the label goes away and you can enter your value into it. Finally, when the input is no longer focused, if there is no value entered, the inline label is then added back in.
My Solution
The title attribute.
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.
Categories
Recent Articles
May 2012
| S | M | T | W | T | F | S |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | ||
| 6 | 7 | 8 | 9 | 10 | 11 | 12 |
| 13 | 14 | 15 | 16 | 17 | 18 | 19 |
| 20 | 21 | 22 | 23 | 24 | 25 | 26 |
| 27 | 28 | 29 | 30 | 31 |
58 Comments
FJ
06.16.2009check also jQuery.fieldtag.js: http://ajaxcssblog.com/jquery/fieldtag-watermark-inputfields/
Joost
06.16.2009Nice idea.
I would add real label elements as well. You can then position those labels off screen with jQuery. That way you have an accessible form that still makes sense when js is not available.
Benjamin Reid
06.16.2009First, good job on explaining the steps to building this, they are really well written.
I’ve been using the jQuery example plugin to do something similar but you have to specify each input field in the JS. Your method using the title attr’ is great and I’ll definitely be using this sort of method in the future.
Thanks for posting.
:)
Andy Pemberton
06.16.2009Agreed; this is a cool technique but I’d prefer using the element over the input title for accessibility and semantics.
Trevor
06.16.2009@Joost-
Absolutely. I would recommend using a regular label as well. Just wanted to focus everyone on the task at hand.
@Benjamin Reid-
Excellent, glad you found it useful.
@Andy Pemberton-
Yeah, I would use both.
Argg
06.16.2009Thanks I’ll be using this!
Ted Goas
06.16.2009Thanks Trevor! I do a lot of form design and have been looking for something like this. Many scripts I come across seem way too large to accomplish something simple. You’ve done it it a clean, concise manner.
Chris Paul
06.16.2009Looks good. Thanks for sharing!
Jules
06.16.2009This is a great technique, but what do you do when you need the field to be “required”? Since there is already text in the field it will pass validation. I’m really hoping you have an answer because it’s what’s kept me from using this idea in past situations.
Thanks for sharing!
Trevor
06.16.2009@Jules-
You will just need to change your validation rules so that it would use JavaScript on submit to check to see if the value is equal to the title attribute.
Jason Persampieri
06.16.2009I think most of us end up doing something similar. The only difference in mine is I invert your ‘class’ usage. Instead of toggling a ‘focus’ class which is set when the element is focused, I toggle an ‘inlinetip’ class which is set only when the tip is being displayed.
That way, I can strip off the values of any element with class ‘inlinetip’ at submission (and immediately re-add it if it’s an AJAX submit).
Jason Persampieri
06.16.2009That said, I’ve considered doing something fancy like overlaying a div above the element with the title-tip. That way you don’t have to deal with ‘data-fixup’ at all. Hmm… perhaps that’s an idea for my first ‘real’ jquery plugin :)
Brian Cray
06.17.2009Try using the input’s defaultValue property instead, then there’s no need to rely on title.
$(‘input’).get(0).defaultValue
Trevor
06.17.2009@Brian Cray-
I’m not sure what you mean. So are you saying to add the value attribute to the input? I was trying to avoid that.
Brian Cray
06.17.2009Trevor: Do you mean you were trying to avoid:
Brian Cray
06.17.2009Retyping with encoding:
<input type=“text” value=“value that will erase on focus />
Trevor
06.17.2009@Brian Cray-
Correct, I do not want to add the value into the actual HTML.
Brian Cray
06.17.2009ahhh… okay, didn’t realize that sorry
Stephen Cronin
06.17.2009It’s a nice approach, but I need to make sure that a) required fields don’t have the default text and b) the optional fields are reset to blank on submit.
I know you said to Jules that we’ll need to change our JavaScript validation rules to cater for this stuff. That’s not a problem, but really we need to modify our server side validation as well, which makes it a little more complicated.
I’m thinking about clever ways to do this - perhaps assign the descriptions to variables, then use them in both processing the _POST values and in generating the form…
Anyway, thanks!
Josh
06.18.2009GREAT example! Thanks for sharing!
Vlad Bazon
06.25.2009Admirable your explanation, I like your style of describing things. I suggest this code reformulation:
$('input[title]').each(function() {
var qinp = $(this), title = qinp.attr('title');
if(qinp.val() === '') qinp.val(title);
qinp.focus(function() {
if(qinp.val() === title)
qinp.val('').addClass('focused');
});
qinp.blur(function() {
if(qinp.val() === '')
qinp.val(title).removeClass('focused');
});
});
Kyoji
08.10.2009Thanx your work. good src!
Liu Peng
08.21.2009Good idea, I will use it in my project!
omar
08.30.2009why all that code when you can just add a form value and:
onclick=“this.value=’’ “
No Jquery or anything else needed..just one line of code in the form.
Am I missing something here??
Trevor
08.30.2009@omar-
Whenever you use JavaScript, you should use it unobtrusively. You should always separate the behavior layer from the content layer.
Matt Richardson
09.29.2009@Trevor, this is a simple piece of code. Just getting into jQuery, and was able to easily adjust this to work with a textarea object.
Thanks for the simple walk through!
Trevor
09.29.2009@Matt Richardson-
Excellent, glad you were able to figure out how to adjust it on your own!
Eric
11.06.2009how would you keep the label being passed as the field value on form submit?
Trevor
11.06.2009@Eric-
I guess you would have to account for it in the JavaScript validation.
Maicon Sobczak
11.27.2009A simple and perfect solution. Instead of add a class to focused input, you can use the css atribute :focus.
Mark
12.30.2009Awesome; But how do you handle passwords and password confirmation fields?
Trevor
12.30.2009@Mark-
You would have to modify the code so that you copy a password field as a regular text field and show that. Then on focus, you want to hide the text field and show the password field.
Scott Bush
02.03.2010Trevor this was a very useful bit of code—thank you for sharing! I implemented it and it worked great.
One thing I discovered later, though: HTML 5 supports an attribute called “placeholder” that does the same thing as your jQuery code. Of course, your approach works in all browsers that support jQuery; currently, only the latest versions of Safari and Chrome support the “placeholder” attribute.
Here are the details:
http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#the-placeholder-attribute
Trevor
02.03.2010@Scott Bush-
Yep, I have seen the placeholder attribute. I have actually started to shy away from this type of inline label because then you have to deal with validating the data. I have actually started absolutely positioning the labels on top of the input field and hiding it when it’s been clicked.
David
03.26.2010Hi Trevor,
Thanks for the great script - so simple it’s untrue!
Quick query - I’m using this in conjunction with your AJAX contact form (validation etc) script. I’ve combined the two scripts and some some other code in there too that slides in a contact form, and then slides it out again once all done. Near the end of the script I have the following to clear the user fields once the form is submitted successfully:
$("#contact_form")[0].reset();It does what it’s supposed to do (i.e. clear the user entries on the form) - however it also clears the labels too. Is there a way to ‘reload’ the inline form labels after the form fields are cleared?
Thanks,
David
Trevor
03.27.2010@David-
You should be able to turn the code to add in the labels into a function. Then after you’ve “reset” the form, just call the function to add the labels back in.
Enzo
04.01.2010Cool, but most forms contain radio buttons & checkboxes, so this doesn’t work. Looks good for a login form though.
Trevor
04.01.2010@Enzo-
Well right, you would have to treat radio buttons & checkboxes differently. As long as you don’t add a title attribute to those inputs, then there are no problems.
Donato
04.01.2010I love your implementation, I’ve been looking through a lot of different ways to do this, and this was really the best.
Well done, thanks!
Martin
04.03.2010I’m looking for a good inline-label plugin, but there is nothing close to this implementation:
https://launchpad.37signals.com/signin
... unfortunately it uses the Prototype framework.
Why it’s good:
- focusing the input fades out the label
- typing in hides the label
- deleting text (using backspace) shows the label again.
- autocomplete doesn’t brake it.
If someone could make the such a plugin with jQuery, many people would be grateful :)
Rob
04.04.2010Great plugin!
Works like a charm and super simple script, unfortunately the use of the Title attribute conflicts with form validation plugin here:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
I’m no jQuery expert so couldn’t figure out a fix. Any ideas would be fantastic :)
Trevor
04.04.2010@Rob-
Another method for displaying inline labels may be better then.
Rob
04.05.2010Great stuff,
I tried out Doug’s method but couldn’t for the life of me figure out why it wouldn’t work in conjunction with my Mail Chimp form code. After lot’s of trial and error I figured out what was going wrong:
First NameTurns out all labels, id’s and names have to be the same or else the javascript wont work!
I am trying out your revised code, works like a charm :)
Bob
05.25.2010@Vlad Bazon-
I like this optimization… Probably faster.
Keri
06.01.2010Thank you! Gorgeous solution. =)
Rachel
06.25.2010I have been implementing this solution and I really do love it, it makes forms so much neater but I have ran into a problem. I use this for a store locator, the user inputs their postcode and then hits go which brings them to a “refine your search” screen. We need the input to remember the postcode value (which it does) but when the user goes to the next screen both the label and value is present within the input. Can you suggest anything that would rectify this?
Rachel
Trevor
06.25.2010@Rachel-
Not sure exactly what you mean. Can you show us?
——-
yasam phani
08.10.2010Thanks for sharing idea..!!!
yasamphani
08.12.2010awesome..!!
Kmus
11.19.2010The same solution using prototype instead:
document.observe(“dom:loaded”, function() {
$$(‘input[data-title]’).each(function(item) {
var data_title = item.readAttribute(‘data-title’);
if(item.value === ‘’) {
item.value = data_title;
}
item.observe(‘focus’, function(event){
if(item.value === data_title) {
item.value = ‘’;
item.addClassName(‘focused’);
}
});
item.observe(‘blur’, function(event){
if(item.value === ‘’) {
item.value = data_title;
item.removeClassName(‘focused’);
}
});
});
});
NOTE: I’m using ‘data-title’ instead of ‘title’ to have a more w3c compliant code.
Dec
01.26.2011Hi, great script! Got it working no problem! Have a quick question though!
My form uses input and textarea tags as below. Can somebody advise me how to modify the script so that is works with both?
Thanks a million!
Dec
<input name=“name” id=“name” title=“Your name” type=“text” />
<textarea name=“message” id=“message” title=“Message”></textarea>
Trevor
01.26.2011@Dec-
Just change your selector to select textareas too. Or use the :input selector.
Behad
02.20.2011Dear Trevor,
I really like your method and want to use it with jQuery validation as seen on the following example:
http://docs.jquery.com/Plugins/validation#Example
But the validation doesn’t work properly if I use inline labels.
It’s a frequently asked question in your comment board. I wonder if you could provide a clear solution and example for newbies like me.
Your help is greatly appreciated!
Behad
Trevor
02.20.2011@Behad-
There are a couple of options:
1. On submit, check to see if the value equals to tittle attribute. If so, then change the value to be blank.
2. Position the labels overtop of the form field
Mario
04.27.2011wow nice script.. but how to make inline label for password type? because when i used this, the label of password type input turn into *****. how to change it into text and back to ***** format when its unfocus. thx.. :D
sorry for my bad english.
Mario
04.27.2011sorry i mean how to change the inline label into text and back to ***** format when its focused.
Trevor
04.27.2011@Mario-
This is a really old tutorial, and there are many other ways to accomplish this. Here is another one I have written about.
Mario
04.28.2011thx very much for reply sir.. i’ll see link u gave to me. :D
Too late, comments are closed!
Don’t worry, you can email me or contact me on Twitter.