A jQuery Function to Auto-Fill Input Fields and Clear them on Click
Wednesday, November 19th, 2008 | Design
***UPDATE 1/27/2010: I have created a github repository for this plugin, and added password field support! ***
Original post which needs to be updated to reflect the changes in the plugin (but the idea is the same):
So you’ve got some input fields, maybe a search bar, or a name field, an email field, whatever. You’d like it to be smooth and show the required info in the field, and have it clear when your customers focus on it. How slick would that be? Well, I have written 12 lines of jQuery that will make your forms even sweeter.
Let’s start with the basics.
First, you need jQuery. I recommend linking the Google-hosted jQuery script, as this may someday help optimize your web site. The idea is that if enough people are using the hosted libraries, then there’s a good chance that your visitors have already cached the file, helping your site load faster.
Next, you need a javascript file for holding all your functions and making calls to those and the built in jQuery libraries. I call mine “functions.js”. So create that and link it after your jQuery script:
<script src="http://www.google.com/jsapi"></script>
<script>
google.load('jquery','1.4.1');
</script>
<script src="js/functions.js" type="text/javascript"></script>
In your HTML, you need an input field. Let’s use a search box for our example.
<input id="txtSearch" type="text" value="Search for Keyword(s)" />
Here we will get a standard textbox with the words “Search for Keyword(s)” in it. Now, we could write a function that clears the text when the user clicks, and it would be very easy, like this:
$("#txtSearch").click(function(){ $(this).attr({ value: '' }); });
We’re presented with a few problems, however:
- The value won’t clear if the visitor doesn’t have JavaScript enabled.
- It only works “on click”. What if the user tabs to your field? Use “on focus” instead.
- The value will clear even if the visitor typed their own text in already. This violates the usability rule that you should always preserve users’ data.
<input id="txtSearch" type="text" />
Now let’s modify our JavaScript to add the default value, and clear it when clicked, but only clear if the default value is in the field.
$("#txtSearch").attr({ value: 'Search for Keyword(s)' }).focus(function(){
if($(this).val()=="Search for Keyword(s)"){
$(this).val("");
}
});
Now we have a search field that gets a default value and clears when the visitor brings focus (through click or tabbing) to the field, but only when the default value is found in the field.
So, what if the visitor tabs through to the next field and forgets what the newly empty field was for?
Did you really think I’d leave this detail out? It’s simple. We add a function to re-fill the field with our default value on blur if the current value is found to be empty:
$("#txtSearch").attr({ value: 'Search for Keyword(s)' }).focus(function(){
if($(this).val()=="Search for Keyword(s)"){
$(this).val("");
}
}).blur(function(){
if($(this).val()==""){
$(this).val("Search for Keyword(s)");
}
});
So can this get any better? You bet! We can make the default value have a lighter text color and give the visitor input a darker color. We can also turn this into a function so it can be applied to any field in our DOM! Let’s do it!
function autoFill(id, v){
$(id).css({ color: "#b2adad" }).attr({ value: v }).focus(function(){
if($(this).val()==v){
$(this).val("").css({ color: "#333" });
}
}).blur(function(){
if($(this).val()==""){
$(this).css({ color: "#b2adad" }).val(v);
}
});
}
Just pass the ID of the field and the default value you want it to have:
autoFill($("#txtSearch"), "Enter Search Keyword(s)");
That’s it, now go check out the demo and feel free to copy!
29 Comments to A jQuery Function to Auto-Fill Input Fields and Clear them on Click
Awesome dude, Just what I was looking for!
January 30, 2009
How can we clear a input FILE field using javascript or jquery.
<input type=”file
F**king sick Joe. Snooks sent me your way. Literally nothing like this I could find on the internet (I’ve spent an hour looking).
Awesome job mate,
L
March 13, 2009
Hi Joe, thanks for that nice script – exactly what I need. Unfortunately it does not work in my application, since this is not executed after loading the site:
$(document).ready = autoFill($(“#txtSearch”), “Enter Search Keyword(s)”);
Although when executing it in Firebug it works as expected. Before that I make some other calls like window.onload etc.
Any idea?
Roman
March 13, 2009
Sorry for bugging, I found the problem … I have to use
$(document).ready(function() {
autoFill($(“#txtSearch”), “Enter Search Keyword(s)”);
});
Anyway, thanks for your script!
Looks good, man. Glad it’s working for you :)
Found your tutorial via google. This is working perfectly for me right now. However, I’d like to add it to a different site and use it on multiple fields within the same form. Unfortunately my jquery kungfu is minimal and I don’t know how to proceed in that direction.
Is it possible? if so, how would I go about that?
Thank you.
Really great post man. Good written and explained. Will use that function of yours for ever probably :p. Thanks for sharing!
Make it a jQuery plugin!
@sean-
Simply add this line to your JS file for each field you want to use:
autofill(‘#field_id’,'Value’);
@sean-
Now that this script is a plugin, call it like so:
$(‘#field_id’).autofill({ value: ‘Default value’ });
for each form field.
You can now customize the default & active text colors by setting them in the function call:
$(‘#field_id’).autofill({
value: ‘Default value’,
defaultTextColor: ‘#f00′,
activeTextColor: ‘#000′
});
Thanks, will try that out in the next couple of days.
April 2, 2009
Thanks, just the ticket!
*subscribed*
April 2, 2009
[...] been getting awesome responses on my autofill jquery plugin and I really appreciate all of it. I’d like to share some more of the things I’ve built [...]
April 2, 2009
[...] A jQuery Function to Auto-Fill Input Fields and Clear them on Click – Joe SakIn addition to guiding you through the JavaScript necessary to make this work, Joe has also written a jQuery plugin to do the work for you. [...]
April 8, 2009
Hey Joe i think what you have done is awesome, i really like it and easy to work with, the problem though that i’m having is that this is not working in IE. Is there some kind of disclaimer that i missed that said this wont work on IE. I keep getting an error of “this object does not support this property or method”…gosh I HATE IE with a passion. When i try loading this page http://www.joesak.com/uploads/demo/autofill.html in IE, I get the same error. any way you can help out would be greatly appreciated. Thanks.
@antonio-
Thank you for your comment. I caught a typo in the plugin that was breaking down in IE6. That’s what I get for abandoning IE6 in my testing phase! :-P
Thanks, everything is updated now.
April 8, 2009
dude you are awesome, thanks for the fix. out of curiosity, you think you will ever add support for password input fields…..I dont really need it, since i created a work around, but it would be pretty sweet if there was functionality for that.
Oh dude it works but it will show asterisks. you can modify it to change the input type attribute if you want it to switch between password and plain text. I’ll add that feature later when I’m not at the bar ;)
Thanks for the feedback!
I have been using a different implementation which is far easier (60% somebody’s elses code which wasn’t working for me): Add a title element to all input fields with the autotext, add two css classes (defaultText and defaultTextActive) and you’re finished. Probably a lot easier then this implementation.
[css]
.defaultText { color: #a1a1a1; }
.defaultTextActive { color: black;}
[/css]
[jquery]
$(“.defaultText”).focus(function(srcc)
{
if ($(this).val() == $(this)[0].title)
{
$(this).addClass(“defaultTextActive”).removeClass(“defaultText”);
$(this).val(“”);
}
});
$(“.defaultText”).blur(function()
{
if ($(this).val() == “”)
{
$(this).removeClass(“defaultTextActive”).addClass(“defaultText”);
$(this).val($(this)[0].title);
}
});
[/jquery]
And if you would want it to work with a password field, first create a normal textfield, but simply add a .attr(“type”,”password”) to the focus and a .attr(“type”,”text”) to the blur (not tested, but should work without a problem)
May 22, 2009
Owesome man…..
Hi Joe – this is great.
I’m a bit of a weekend bodger with jQuery (rolls eyes).
Is there an easy way to get this to work for textareas – they don’t use value for default content…
Cheers.
July 21, 2009
Hey, I figured out a better way, meaning you don’t have to pass the value all the time for specific inputs, just use the rel attribute.
So the input element is like:
The script is like this:
$(‘input’).focus(function() {
if($(this).val() == $(this).attr(‘rel’)) {
$(this).val(“”);
}
}).blur(function() {
if($(this).val() == “”) {
$(this).val($(this).attr(‘rel’));
}
});
I find this much handier to maintain than a separate plugin, but cheers for the idea!
July 21, 2009
damn cms blocked my input, but it should be like {input type=”text” rel=”NAME” value=”NAME” /}
July 27, 2009
To add on to Aaron Mc Adam you could add a .blur() to the end of the chain which would fire the blur event on each input element and you would then only need to add the rel attribute for each input instead of the rel and the value.
November 20, 2009
Hi Joe,
How would you go about modifying this to work on a password field?
you are fckin awesome man! brilliant stuff, way to go dude.
I hope you guys get this. I updated the plugin to have automatic support for password fields. Just use it like normal on your password field and you’re golden!
March 10, 2010
Thank you so much.. awesome stuff.. its just what i was looking for..
Leave a comment
Search
Tweetin'
- @ashetler I'm reading Atlas Shrugged right now and I'm way into it. (@leslie_pearlman) -- I just started it! We could read it together!
- You guys know there's a @cardsink 2.0 right? http://www.cardsink.com -- it's live! What do y'all think?
- Cleanin' up a bit for @semivanj and @laurenmoll's weekend visit!
- @SahSahSarah oh man, yea.
- RT @the_gordon Cyclist killed in crash in Okemos, MI this morning http://tinyurl.com/y97dyf5 It is a terrible thing : (
November 21, 2008