How to store checkbox state in localstorage with jquery

Hi,

I have some code which remembers my checkbox states which I'm trying to change so that it stores the state of each checkbox in localstorage and recalls it on document load, so that even if you close the browser it will still remember the state of each checkbox.

 $(document).ready(function() { 
        // Set aside the original state of each checkbox.
        $("input.toggle").each(function() {
            $(this).data("originallyChecked", $(this).is(":checked"));
			localStorage.setItem(chkbox, originallyChecked);
        }); 
        // Check whether it really changed on click.
        $("input.toggle").change(function() {
            var action = $(this).siblings("span");          
        });
    }); 
 		$(document).ready(function() {
   			 $("input#select-all").click(function() {
       		 $("input.toggle").attr('checked', this.checked);
        	$("input.toggle").change();
   		 });
	});

Open in new window

grahammilesAsked:
Who is Participating?
 
darren-w-Connect With a Mentor Commented:
Hi,  here is an example of it working, as long as the values differ it should work in any environment.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <title>demo</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
        <script src="js/jquery.cookie.js"type="text/javascript"></script>
        <script type="text/javascript">

            $(function() {
                $("input:checkbox").each(function(){
                    if (localStorage.getItem(this.value) == 'checked'){
                        $(this).attr("checked","true")
                    }
                })
              
                $("input:checkbox").click(function(){
                    $(this+":checked").each(function(){
                        localStorage.setItem(this.value,'checked');
                    })
                    $(this+":not(:checked)").each(function(){
                        localStorage.removeItem(this.value);
                    })
                })
            });


        </script>

    </head>
    <body>

        <form>
            <input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
            <input type="checkbox" name="vehicle" value="Car" /> I have a car
        </form>

    </body>
</html>

Open in new window

0
 
darren-w-Commented:
Hi,

This could be done by holding the settings in a  cookie.

Darren
0
 
grahammilesAuthor Commented:
Thanks, but I would prefer to hold them in localstorage, I'm just not sure how.

The line i added: localStorage.setItem(chkbox, originallyChecked) doesn't work. I'm a novice and not very good at reading jquery code...
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
Gurvinder Pal SinghCommented:
$(document).ready(function(){
  $("input.toggle").each(function() {
       var savedValue = localStorage.getItem( $(this).attr("id") );
       if ( savedValue )
       {
            $('input[name=foo]').attr('checked', true);
       }
  });

  $("input.toggle").bind("click", function(){
      localStorage.setItem($(this).attr("id"), $(this).attr('checked'));
  });

});

0
 
grahammilesAuthor Commented:
Thanks gurvinder, that looks good but unfortuanely didn't seem to work. I thought it might be because I'm using the checkbox id's elsewhere on the page so I added some new varaibles but it still isn't storing anything in localstorage..

 $(document).ready(function(){
  $("input.toggle").each(function() {
       var savedValue = localStorage.getItem($(this).attr("id"));
       if (savedValue)
       {
            $('input[name=foo]').attr('checked', true);
       }
  });

  $("input.toggle").bind("click", function(){
     var cbid = $(this).attr("id");
	var chval = $(this).attr('checked');
	 localStorage.setItem(chkbox, chval);
	 alert(chval);
  });

});

Open in new window

0
 
Gurvinder Pal SinghCommented:
it should be

$(document).ready(function(){
  $("input.toggle").each(function() {
       var savedValue = localStorage.getItem($(this).attr("id"));
       if (savedValue)
       {
            $(this).attr('checked', true);
       }
  });

  $("input.toggle").bind("click", function(){
     var cbid = $(this).attr("id");
      var chval = $(this).attr('checked');
       localStorage.setItem( cbid , chval);
       alert(chval);
  });

});
0
 
grahammilesAuthor Commented:
Still not seeing anything at all stored in localstorage.

Could it be due to a conflict with a different function on my page that also stores a string in localstorage when the checkbox is checked..?
0
 
grahammilesAuthor Commented:
Cool! That works perfectly. Thanks Darren-w, you really are a coding guru...!

Thanks gurvinder too, you are undoubtable a genius too and i'm sure it was likely my coding that was the problem...

Many thanks again to both of you!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.