Link to home
Avatar of maqskywalker
maqskywalker

asked on

using jquery to retain a variable set in button click event to be available after page refresh

i have a html page where i'm using jquery

In my jquery i have this code

        $(document).ready(function () {
            // -------------------

            // *********** On Page Load ***********
				
            // copy variable called testvariable1 to a variable called testvariable2
            var testvariable2 = testvariable1;
            
            
            // *********** On Page Load ***********

            
            // *********** button click event  ***********
            $('.Button1Class').click(function () {

                // on button click set variable called testvariable1 to 2
                var testvariable1 = 2;
                
            });
           // *********** button click event  ***********
            
            
            // -------------------
        });

Open in new window


in my button click event, on button click a variable called testvariable2 is set to 2.

I want to copy testvariable1 to another variable called testvariable2 in the pageload event.

But i noticed the above code doesn't work because the variable i set in the button click is lost when I do a page refresh.

I read that I could use localstorage.

so then if I change my button click event to this, then  testvariable2 would be available on page load.

            // *********** button click event  ***********
            $('.Button1Class').click(function () {

                // on button lick set variable called testvariable1 to 2
                var testvariable1 = 2;
               
                // copy variable testvariable1 to testvariable2 to localstorage for use on page load
                var testvariable2 = testvariable1;
                localStorage.setItem("testvariable2", testvariable2);

            });
           // *********** button click event  ***********


Is there better way to copy a variable from button click event to be available after a page reload?
ASKER CERTIFIED SOLUTION
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial