Search code examples
javascriptjqueryhtmlsession-storage

How can I get this javascript var to work across HTML pages?


Page 1:

<html>
<head>
</head>
<body>
    <input type="checkbox" class="checkbox" name="item" value="X">Value X<br>
    <input type="checkbox" class="checkbox" name="item" value="Y">Value Y<br>
    <script type='text/javascript'>
        var score = 0;
        $('.checkbox').click (function(){
          var thisCheck = $(this);

          if ( thisCheck.is(':checked') ) {
            score = score + 1;
          }
        });
        sessionStorage.score = score;
    </script>
    <button type="button" onclick="window.location.href='page2.html'">Continue</button>
</body>
</html>

Page 2:

<html>
<head>
</head>
<body>
    <script type='text/javascript'>
    var score = sessionStorage.getItem('score');
    document.write(score);
    </script>
</body>
</html>

Page 2 always prints null. How can I fix this?
(If both checkboxes were selected, we need page 2 to print 2, for example)

Thanks!

N.B. I know that there is an easy solution to this by having a form action write to an asp file and then reading that, but I can't create new files on this system.


Solution

  • I found the solution. score was being parsed as something other than an Int for whatever reason.

    Using score = parseInt(score) + 1; solved the problem.

    Thanks to everyone who submitted answers! We got there in the end.