Reputation: 173
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.
Upvotes: 1
Views: 92
Reputation: 173
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.
Upvotes: 0
Reputation: 193301
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.
Upvotes: 0
Reputation: 26
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.
Upvotes: 1
Reputation: 35
You are not setting the session well, you need to do this you need to
sessionStorage.setItem("score", score)
Upvotes: 0