How to persist checkbox checked state after page reload

This quick tip describes how to have your browser remember the state of checkboxes once a page has been refreshed or a user navigates away from your site to come back at a later date.

It might be useful to Persist Checkbox Checked State if, for example, you use checkboxes to allow your users to set site-specific preferences, such as opening external links in a new window or hiding certain page elements.

Read the complete article on SitePoint

This post currently has 55 responses

  1. Chinmay says:

    Thank you for sharing your code. I have tried this code , but somehow the value of the checkbox is not retained after reload. It goes back to being unchecked. Do you know why ?

    • hibbard.eu says:

      Hi,

      Are you getting any errors in the console?
      Are you testing locally?
      I ask, as some browsers don’t support cookies for local files.

  2. Jaime says:

    Hello,

    Thank you for sharing your work with us. I am trying to put a reset button in demo-1 to delete the values in checkboxes but so far can´t work out how to do so.

    Can you help me? I would really appreciate it!

    • hibbard.eu says:

      Hi,

      Sure, something like this should work:

      $("button").on("click", function() {
        $.removeCookie('cookie-name');
        $("input:checked").each(function(){
          $(this).prop("checked", false);
        });
      });

      This is untested, so if it doesn’t work, let me know.

      • Jaime says:

        Thank you for your code but unfortunately I couldn’t make your code work. But I managed to make it work with the code below:

        $(“button”).on(“click”, function() {
          $.cookie(‘checkboxValues’, null, { path: ‘/’ });
          $(“input:checked”).each(function(){
            $(this).prop(“checked”, false);
          });
        });

        How could I include type radio buttons in demo-1?

        Thank you for your time! 🙂

  3. Hi,
    Thank you for your code,
    but i want to reload my current page, when checkbox has been checked(clicked).
    so, how can i do this?

    • admin says:

      Hi,

      You can reload a page using JavaScript, thus:

      location.reload();

      But I’m curious. Why do you want to do that?

  4. Bobby says:

    How would you convert the ‘$’ to work with wordpress?

    • admin says:

      Hi,

      I’m not overly sure what you are asking, but maybe something like this:

      (function($) {
        // The dollar alias is available here	
      })( jQuery );
  5. manuelitosimoi says:

    How can we set the cookies to expire at a certain time (for example 8:00:00 a.m in the morning)and would probably have a prompt “cookies expire” then refresh the page.
    and after 8:00:01 a.m it can accept new cookies again.

    • admin says:

      Hi manuelitosimoi,

      Glad you liked the script.
      Instead of a number you can pass $.cookie a Date instance, this allows you to specify the exact time until expiration.

  6. manuelitosimoi says:

    BTW this really really helped me a lot! thank you for sharing!

  7. zee says:

    Hi
    I need some help I have a button remove, I want to remove a particular div based on the selection of a checkbox. Meaning that if the checkbox is checked the div must be removed onclick of the remove button
    Can you please provide the example using javascript / jquery

    Thanks in advance

    • admin says:

      Hi zee,

      The comments section of my blog are a bad place to discuss code issues.

      Instead, please head to SitePoint forums, open an account and post your question in the JavaScript forum.

      If you let me know when you have doen that, I’ll answer you there.

  8. Bobby says:

    Have to tried to integrate this script into WordPress? Im having an issue getting the checkboxes to repopulate

  9. kake says:

    It works great on newer browsers. Do you have a fix for this on IE8?

    Thanks,

    K

    • admin says:

      Hi,

      Object.keys will fail on IE8, so you’ll probably want to have a look at that.

      Personally, I have zero interest in keeping IE8 alive – it is an obsolete browser and should be treated as such.

  10. Arshad says:

    Hi Admin.
    I have downloaded the above example. It is working fine on my local server. But when i try to use like:
    [$.cookie(‘reg_no’, reg_no, { expires: 7})] and [$.cookie.json = true;]
    with jquery code, It is showing error “TypeError: $.cookie is undefined”.

    I have even included CDN.

    Please help.

  11. Chuck says:

    Thanks for the code. I’m starting to love jquery.

  12. Naveen N says:

    Hi Admin,

    I was building a filter you can assume it similar to flipkart or any ecommerce site, where in on each checkbox check the page is reloaded with the required parameters through url(querystring) and by sending the ajax request data of checkbox values data is fetched whether they use the same technique i’m just curious to know (and i assume they are reloading page with querystring for seo purpose)

    • admin says:

      Hi Naveen,

      I’m afraid I didn’t quite get your question.

      Regarding SEO and AJAX, it is quite possible to create crawlable AJAX-driven websites, as this article shows.

      • Naveen says:

        HI admin,
        My question was ecommerce sites use checkbox filters when reloading but the reloading of only the product takes place where as the filters doesn’t get reloaded whether it is page caching or they use persistent checkboxes and i have downloaded the code and used it whether cookie can be set once the page reloads with different querystring for eg when i click on the demo link first time it is empty when i check it and close it and when i click on demo link again the checkbox state remains , i want this behaviour only if the page reloads with query string is this possible how to achieve it

        • admin says:

          Hi,

          I still don’t understand your question. Sorry.
          Punctuation and shorter sentences would make it easier to digest.

  13. Mike says:

    Thanks a lot. But I want to be able to implement this code using radio button instead.

  14. John says:

    Thanks for the code! This is what I’ve been scouring the internets for. One problem, I have been trying to embed multiple check boxes and can’t seem to get them to respond individually. The checks stay marked but they ALL stay marked. Thoughts?

    • admin says:

      Hi,

      It’s hard to say what is going wrong for you without seeing some code.

      Please head to SitePoint forums, open an account and post your question in the JavaScript forum.

      If you let me know when you have done that (e.g. via Twitter), I’ll answer you there.

  15. Kathy says:

    How do you clear the cookie? After adding that code to my page, it seems to be holding on to data, even after I’ve removed your code completely from the page! I assume it will hold on to the data for 7 days since that is what I had in the cookie. Thanks!

  16. Alan says:

    Thanks for this great tutorial!

    Ive tested in one page locally with IE and it works perfectly.

    I would like to implement a few pages, each with a list of items that can be checked or uncheck, but it appears that using the same code in another page interferes even when the input have different id names. It may work on each page independently while they are all open in the browser, but after I close the browser only the last page to be modified keeps the values.

    Right now Im not sure which part of the code I can change to identify a given page to be different from other page files with similar code.

    • admin says:

      Thanks for your comments Alan.

      This is something I can help you with, but not really in the comments section of my blog.

      The best thing to do is to head to http://community.sitepoint.com, create an account (or login using Google, Facebook, Twitter, Yahoo or Github), then create a topic with your question in the JavaScript forum. Let me know when you have done that and I’ll answer you there.

  17. Lars says:

    Thanks for the script. However I’m getting an error when running it with IE8 and jquery 1.7.2. The error is “Object doesn’t support this property or method” and it gives this error on line 60 in your code. The line that begins with “Object.keys(elementValues)…”

  18. Lars says:

    Scratch that! Found out that Object.keys dont work with IE < 9.

    Cheers

  19. paul says:

    Thanks for this great script.
    I work with php while loop and i don’t have “id”, can I use “name” instead ?
    Thank you !

  20. Isi says:

    Hi,
    thanks for sharing your code! 🙂
    So far, I have just copied it 1:1 but for some reason, its not working for me while your demos here work perfectly fine. Here’s the page: https://mars.iuk.hdm-stuttgart.de/~im031/NEU/Blog.html
    You dont happen to have any idea why?
    Thanks in advance!

    • admin says:

      Hi,

      Thanks for your comments.

      The problem with your page is that it is using https, yet you are loading the assets (jQuery and the cookie script) via http.

      One solution to this would be to download these files yourself and include them locally, i.e.

      <script src="/path/to/jQuery/on/your/server">
      
  21. sampath says:

    An awesome explanation. Thank you very much

  22. Scott says:

    Thanks for the script – it works great!
    How could I apply this to a textbox field; so it saves the field data for the 7 days?
    Ideally I would like the checkbox, then the textbox right next to it.

    Thanks!

    • admin says:

      Hi,
      I would save the value of the text input in the cookie and set the cookie to expire after seven days.

      • Scott says:

        Do you have some sort of example of how this could work? I’m stumped at this point…

        Thanks 🙂

        • admin says:

          I don’t have much time right now, but if you head to http://community.sitepoint.com open an account and post your question with the code you have in the JavaScript forum, I will answer you there.

          Also, pls let me know when you have done this (e.g. via my contact form).

Comments are closed!

I'm on Twitter:

Categories