Ok, so I have a few loves in my life. In web technologies, my love rests in design, jQuery programming and JavaScript, CSS and XHTML. I love playing around with interfaces and front-end UI design and website design. Today, I’m gonna bust out a short post on how I used a snippet of jQuery code to remember my user data, i.e. Name, website, email address, etc. to help out your users a wee bit.

First, an example

Let’s create a text input that we want to be remembered. I’ll give the the every-so-appropriate name of fav_starbucks_drink Here it is:

For all you n00bs out there, the XHTML code is:

<input name="fav_starbucks_drink" type="text" />

Test this jQuery code out by entering in a value in the input and then refreshing the page.

jQuery Code:

Realize two things. You’ll need the jQuery cookie plugin as well as a link to jQuery itself. We are going to be using the cookie plugin to cookie or save the user’s data.

function remember( selector ){
$(selector).each(
function(){
//if this item has been cookied, restore it
var name = $(this).attr('name');
if( $.cookie( name ) ){
$(this).val( $.cookie(name) );
}
//assign a change function to the item to cookie it
$(this).change(
function(){
$.cookie(name, $(this).val(), { path: '/', expires: 365 });
}
);
}
);
}

Restoring saved field values

Aight. Let’s just dive into explaining this hunk of code. First, you will notice the function declaration:
function remember( selector ){

The function parameter selector is a jQuery selector, which happens to be either a CSS3 selector that targets the desired inputs or a collection of jQuery objects.

Next:

$(selector).each( function{...

$.each is a sweet function that executes the function passed in as it’s argument for every object within the jQuery collection as created by the selector parameter. If you are lost at this point, let it suffice to say that we are going to loop through all of the input items as identified by their selectors.

Now, lets digest a bigger chunk. This next segment of code will perform the function of restoring any saved values. Now, hopefully this script is being ran on page load, so this restore segment will restore the field values on page load. Here’s that jazzy code now:

var name = $(this).attr('name');
if( $.cookie( name ) ){
$(this).val( $.cookie(name) );
}

First, a variable name is created and set to the attribute of name on the input item. What does that mean you ask? Well, basically we don’t know the selector that targeted this input, but we want to store the name of the form item as we aren’t guaranteed we will have an id. Cool now the name attribute of the input is stored in the var of name, so fittingly named.

Next, the code is if( $.cookie( name ) ). What’s that mean? Think of it like this: “Is there a cookie with this name”? Okay, so if we have cookied the value for this input, it’ll be in that cookie. Radness. Okay, if there is a cookie, set this input item’s value attribute to that value. Simple eh? By using the $.val() function, I can set the value if I pass a parameter or I can get a value by leaving params emtpy. Eazy peezy – set the value to the cookie with that name:

$(this).val( $.cookie(name) );

Ok, now we have code for all input items of type text and textareas to be set. We won’t cover checkboxes, radio’s and select lists on this post.

Creating functions to save field values on change

This block of code is uber simple. Check it:

$(this).change(
function(){
$.cookie(name, $(this).val(), { path: '/', expires: 365 });
}
);

Guess what $(this).change() does? That’s right, it creates an onchange function handler for the targeted input item. So whatever function we pass the change function will be ran when input item’s value is changed. Word.

Wow, this one is easy. Guess what, when this input item gets changed, cookie it. That’s it. In plain english, we are naming the cookie the name of the input item, we are assigning it the value of the input, it’s path is the root of the site and it expires 1 year from now. Rocking.

Last, lets run the code. Do that by calling the function, passing it the selector to target the item. Something like this will suffice:

remember( '[name=fav_starbucks_drink]' );

Ooh, check that out, I used an attribute selector, which since jQuery supports up to CSS3 selectors, will actually work on IE6. ;)

You could also run the code as soon as the document is ready by doing something like this:

$(document).ready(
function(){
remember( '[name=fav_starbucks_drink]' );
}
);

That’s it. This code could obviously be improved no doubt, including handlers for select, checkboxes, radios and more, but you get the gist. This script was uber easy to bust out. I heart jQuery. Do you?

Comments

25 Comments

  1. Daniel said over 2 years ago

    Nice work Rogie. jQuery is a pretty powerful tool and it’s good to see you’re making the most of it =) Keep it up!

  2. Collin said over 2 years ago

    I, too, <3 jQuery!

  3. Davor Pei? said over 2 years ago

    great tut! this also can be used for other things, for example I never used jQuery cookie plugin, now I could learn it.

    Thanx!!!

  4. Ramesh Soni said over 2 years ago

    good post..

  5. Rogie said over 2 years ago

    @Collin You get soooo emotional when jQuery gets talked about, I know. It’s like when the teacher starts boasting about your child….you just start glowing.

    @Davor Pei – The cookie plugin is rockin’. I’m using it for the foliage-o-meter to save the foliage level as well as for saving form inputs. Have fun!

  6. Larry Marburger said over 2 years ago

    Great idea, Rogie!

  7. söve said over 2 years ago

    thank you..

  8. Juan Pablo said over 2 years ago

    jQuery Rocks!!! I just love it. I didnt know about this plugin but I think Im gonna use it

  9. Simon said over 2 years ago

    $(document).ready(….

    $(function() {
    remember(‘[name=fav_starbucks_drink]‘);
    });

    Gotta save those precious bytes ;)

  10. temizlik said over 2 years ago

    thank you….

  11. Marcelo Graciolli said over 2 years ago

    This Blog is very Pretty, very cool!!!

  12. Marcelo Graciolli said over 2 years ago

    I want a blog!!!

  13. Guillermo Rauch said over 2 years ago

    I don’t think it’s a good idea to store form information in cookies.
    Cookies are sent in headers in *every* request. You should pay attention to what you add to them, and if they can be avoided (like in this case), they should be avoided. For example. this script would be specially troublesome if the form included a textarea, or if it had many fields. In the real world, no one has a single textfield prompting to write the favorite beverage :P
    There’re better ways to implement this functionality. Look into other permanent local storage options.

  14. Rogie said over 2 years ago

    @Guillermo –

    In the real world, no one has a single textfield prompting to write the favorite beverage.

    Sure, thats understood, however saving form data via cookies is (to me at least) a helpful solution for some problems. Case in point: This comment form. Say you wanted to comment every day on this blog. Would you like to have to fill your information in every single time? I think not. Why not give you a hand and throw your data in for you? Also, this solution is simplified for tutorial’s sake. In the real world, textarea, checkboxes, etc would need to be accounted for ;)

  15. Benje said over 2 years ago

    I love your site, you are a talented designer! This is the most functional personal site I have ever seen :)

  16. Brendan Falkowski said over 2 years ago

    Loving it, nice to have a plain English explanation of the code for beginners to the jQuery hotness.

  17. Ramakant Prajapati: Journal » Blog Archive » Using jQuery to save form details said over 2 years ago

    [...] Test this jQuery code out by entering in a value in the input and then refreshing the page. [...]

  18. Max said over 2 years ago

    SEXY! Thank for that :-D Love it.

  19. Eduardo Sasso said over 2 years ago

    Great script, it was exactly what i was looking for, worked like a charm. Thanks

  20. forklift said over 1 year ago

    thank you for sharing

  21. “The Complete Guide” for jQuery Developer- Reblog « Dynamic Disruption said over 1 year ago

    [...] Using jQuery to Save Form DetailsSave form details to make your forms more friendly to your visitors (and increase sign-ups). [...]

  22. Bookmarks about Jquery said over 1 year ago

    [...] – bookmarked by 2 members originally found by tahirbutt on 2008-08-11 Using jQuery to save form details http://www.komodomedia.com/blog/2008/07/using-jquery-to-save-form-details/ – bookmarked by 5 [...]

  23. Aaron said over 1 year ago

    GREAT code!

    Is there a way to have it auto parse all fields on a page and not have to enter each one in the code manualy?

    This way you could have a very long form or forms with similar fields and when you went to the pages it would populate the fileds for you. :)

    Thanks again for such an awesome script! :)

  24. Jerome said over 1 year ago

    Im newb, and this will definitely come in handy, but your illustration of the vine on this comment div and more strikingly on the upper left of the header are unbelievable. The shadows are just right, I just wanna stare at it for hours!

  25. M.A.Yoosuf said over 1 year ago

    Thank you , i got the exact usage trend from this article

Sorry, the comment form is closed at this time.