RSS
 

A jQuery Function to Auto-Fill Input Fields and Clear them on Click

19 Nov

/!\ UPDATE 7/14/2010 /!\

HTML5 now supports the ‘placeholder’ attribute, which essentially renders my plugin useless.
I have started an html5 branch on the github repo, and will have a new version up soon that checks browser support and only triggers on older browsers. The “value” option will be deprecated in favor of the placeholder attribute.

***UPDATE 1/27/2010: I have created a github repository for this plugin, and added password field support! ***

Download the plugin here.

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:

  1. The value won’t clear if the visitor doesn’t have JavaScript enabled.
  2. It only works “on click”. What if the user tabs to your field? Use “on focus” instead.
  3. 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.
So what steps can we take to fix this? First, let’s remove the default value from the HTML:
 <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!

 
31 Comments

Posted in Design

 

Leave a Reply

 
 
  1. steve Swinsburg

    November 21, 2008 at 9:18 am

    Awesome dude, Just what I was looking for!

     
  2. Neeraj

    January 30, 2009 at 12:07 am

    How can we clear a input FILE field using javascript or jquery.
    <input type=”file

     
  3. Lewis Litanzios

    March 8, 2009 at 11:41 pm

    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

     
  4. roman

    March 13, 2009 at 6:45 am

    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

     
  5. roman

    March 13, 2009 at 7:27 am

    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!

     
  6. Joe Sak

    March 13, 2009 at 8:03 am

    Looks good, man. Glad it’s working for you :)

     
  7. Sean

    March 14, 2009 at 2:44 am

    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.

     
  8. d0ri0

    March 17, 2009 at 11:46 am

    Really great post man. Good written and explained. Will use that function of yours for ever probably :p. Thanks for sharing!

     
  9. Roger

    March 17, 2009 at 2:44 pm

    Make it a jQuery plugin!

     
  10. Joe Sak

    March 23, 2009 at 12:17 pm

    @sean-

    Simply add this line to your JS file for each field you want to use:

    autofill(‘#field_id’,'Value’);

     
  11. Joe Sak

    March 23, 2009 at 1:23 pm

    @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′
    });

     
  12. Sean

    March 23, 2009 at 4:08 pm

    Thanks, will try that out in the next couple of days.

     
  13. Simon

    April 2, 2009 at 7:35 am

    Thanks, just the ticket!
    *subscribed*

     
  14. Guys I’m still here! – Joe Sak

    April 2, 2009 at 10:54 am

    [...] 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 [...]

     
  15. Tech Messages | 2009-04-02 | Slaptijack

    April 2, 2009 at 2:17 pm

    [...] 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. [...]

     
  16. Antonio

    April 8, 2009 at 8:01 am

    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.

     
  17. Joe Sak

    April 8, 2009 at 9:20 am

    @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.

     
  18. Antonio

    April 8, 2009 at 8:29 pm

    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.

     
  19. Joe

    April 8, 2009 at 9:19 pm

    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!

     
  20. David Mulder

    April 9, 2009 at 4:52 am

    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)

     
  21. Aneeq

    May 22, 2009 at 3:33 pm

    Owesome man…..

     
  22. Gareth Price

    July 15, 2009 at 7:17 am

    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.

     
  23. Aaron Mc Adam

    July 21, 2009 at 3:38 am

    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!

     
  24. Aaron Mc Adam

    July 21, 2009 at 3:40 am

    damn cms blocked my input, but it should be like {input type=”text” rel=”NAME” value=”NAME” /}

     
  25. Josh Rhykerd

    July 27, 2009 at 2:28 pm

    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.

     
  26. Marcus

    November 20, 2009 at 12:56 am

    Hi Joe,

    How would you go about modifying this to work on a password field?

     
  27. Asko

    December 29, 2009 at 8:31 pm

    you are fckin awesome man! brilliant stuff, way to go dude.

     
  28. Joe Sak

    January 28, 2010 at 8:52 pm

    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!

     
  29. kal

    March 10, 2010 at 11:04 am

    Thank you so much.. awesome stuff.. its just what i was looking for..

     
  30. Amy

    April 16, 2010 at 10:26 am

    I modified the js file to allow prepopulated data in the fields such as Address, City, State, Zip, Email.

    So if there is data in the field, don’t fill in the default value otherwise use the default value.

     
  31. Nick

    July 1, 2010 at 1:11 am

    Thank you for taking the time to write this. I was going to hand write it, but decided there’s no point in reinventing the wheel — thanks!