user2586455 user2586455 - 7 months ago 28
Javascript Question

How to use Javascript to keep a running score on multiple choice

I've been trying to work this one out for ages, but just can't seem to wrap my brain around it.

Here's my HTML:

<select>
<option value="0">Select</option>
<option value="-5">Answer 1</option>
<option value="5">Answer 2</option>
</select>

<select>
<option value="0">Select</option>
<option value="-5">Answer 1</option>
<option value="5">Answer 2</option>
</select>

<p class="total">0</p>


And here's my JS:

var score = 0;
var scoreNew = 0;
$('select').change(function() {
scoreNew = parseInt($(this).val()) + parseInt(score);
$('.total').text(scoreNew);
})


What happens:


  • If you select Answer 1, the score is -5

  • If you select Answer 2, the score is 5 (so far so good)

  • But if you then go to Q2 and select Ans1, the score goes to -5 (whereas it should now be 0)



I thought I fixed it with the following code (but I didn't):

var score = 0;
var scoreNew = 0;
$('select').change(function() {
scoreNew += Number($(this).val());
$('.total').text(scoreNew);
})


What happens now:


  • If I select Ans1, I get -5 (so far so good)

  • But if I then select Ans2, I get 0 (where it should be 5)



I feel like I almost need a combination of those 2 methods, but can't quite figure it out.

I hope that all makes sense. If anyone can help it would be hugely appreciated. Thank you.

Rob Rob
Answer

Because you've declared total outside the scope of your change handler, it will retain its last assigned value and therefore any further changes will be applied to the updated total rather than the original one of 0.

If you need to update on each select, you should declare the variable locally and recalculate using all the current values of your select elements:

$('select').change(function() {
  var total = 0;
  $('select').each(function() {
    total += Number($(this).val());
  });
  $('.total').text(total);
})

Fiddle: https://jsfiddle.net/zgj6sq05/