1

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.

Tedfoo
  • 163
  • 2
  • 11
  • @RoryMcCrossan With HTML5 this is very possible. For example: `var score = 2; sessionStorage.score = score;` on one page and `var score = sessionStorage.getItem('score'); document.write(score);` on a second page works absolutely fine. – Tedfoo Mar 29 '15 at 15:40
  • Oh yeah, my bad, forgot about sessionStorage. – Rory McCrossan Mar 29 '15 at 15:43

4 Answers4

1

First neither of your checkboxes actually have a class of 'checkbox' so that jquery event will never fire even if you check one of the checkboxes.

Also, you are declaring the variable as thisCheck but trying to access it using thischeck (notice the lower-case c). Javacript is case-sensitive so 'thischeck' is never being assigned a value.

0

You are not setting the session well, you need to do this you need to sessionStorage.setItem("score", score)

0

You need to set sessionStorage value on each click:

var score = 0;
$('.checkbox').click (function() {
  if (this.checked) {
      score = score + 1;
  }
  sessionStorage.score = score;
});
sessionStorage.score = score;

Note, that if probably want to deduct 1, if checkbox is unchecked, in this case try this code:

var score = 0;
sessionStorage.score = score;

$('.checkbox').click (function() {
    score = score + (this.checked ? 1 : -1);
    sessionStorage.score = score;
});

And btw, you need to add class="checkbox" to inputs.

dfsq
  • 191,768
  • 25
  • 236
  • 258
0

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.

Tedfoo
  • 163
  • 2
  • 11