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:
Solution 1:
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/
Solution 2:
Here's your problem
var score = 0;
var scoreNew = 0;
$('select').change(function() {
scoreNew = parseInt($(this).val()) + parseInt(score); //score is always 0
$('.total').text(scoreNew);
})
You add the new score to 0. Change that line to
scoreNew += parseInt($(this).val());
and get rid of the score
var. Not sure why it's there?
Edit:
Updated method
$('select').change(function() {
var score = 0// run through each value and rebuild score
$('select').each(function(){
score += parseInt($(this).val())
})
$('.total').text(score);
})
It rebuilds the score on every change. Seems lame but it's quite fast.
I'm hoping this is a "test" project since nothing here is production level.
Here's a fiddle if you can't get it to work.
Post a Comment for "How To Use Javascript To Keep A Running Score On Multiple Choice"