jQuery Snippet: Self clearing text fields
Here’s a very, quick, easy javascript snippet. Non front end developers should look away now.
An increasingly popular technique for laying out forms is to combine the label tag and the input tag into one succinct element (as demonstrated in the search box on this blog). This technique cleans up your page and leaves more real estate for user input. A big downside, however, is that you have to add an extra dose of javascript to make your text fields behave as they should.
The behavior that we’re after is simple: When a user comes to your form, if they focus on a text field it should clear it’s label without any effort by the user. If the user decides to navigate away from that field without entering anything, the field should remember it’s what it’s for and repopulate.
Back in the dark ages (when I was a javascript padowan), I used to write specific bits of code to achieve this effect, since every input element had a unique label, and I had to remember what that label was. There had to be a better way to do it; All this was doing was bloating my code. Then, one dreary Wednesday afternoon while slogging through the dom, I came across the attribute “defaultValue”.
w3c defines defaultValue as:
The default value specified in an attribute or an element declaration or null if unspecified. If the schema is a W3C XML schema, this is the canonical lexical representation of the default value.
Exactly the attribute I was looking for. A few minutes later, this handy snippet of jQuery was born:
$('input:text').focus(function(){
if($(this).val() == $(this).attr('defaultValue')){
$(this).val('');
}
});
$('input:text').blur(function(){
if($(this).val() == ''){
$(this).val($(this).attr('defaultValue'));
}
});
Quick & easy. Tested and working in IE6+, Firefox, Safari, Chrome, Opera, etc. etc. etc. Feel free to use it wherever you want to. Also, if you have any suggestions about how to improve this snippet, let me know!
No Comments
No comments yet!
Leave a Reply
We reserve the right to moderate anything that we deem fit. Please note that if your comment does require moderation, we will sell your email address to Spammers-R-Us.
If you want an icon of your own, head over to gravatar and sign up.
© 2012
Not cool enough for twitter? Become a fan of us on Facebook.