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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
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
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

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
darren-w-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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.