The error in logic here is that you are incrementing score regardless of whether or not it already was incremented for a correct answer to a given question and not decrementing score if a correct answer becomes an incorrect one. There could be other conceptual ways of doing this, and there are certainly other coding methods that could be used. My approach was to keep track of when a point was awarded for a question (changes/additions highlighted):
Code:
<script>
var answers = {
'question': 'yes',
'question1': 'no',
};
var score = 0;
function checkResults() {
var $this = $(this),
val = $this.val().toLowerCase();
for (var k in answers) {
if (answers.hasOwnProperty(k)) {
if (k == $this.attr('id') && answers[k] === val) {
$this.css('background-color', 'green');
!$this.data('awarded') && ++score;
$this.data('awarded', true);
break;
} else {
$this.css('background-color', 'red');
if($this.data('awarded')){
$this.data('awarded', false);
--score;
}
}
}
}
/* if (score == 2) {
alert('Hi Ur Score is 2');
} */
$('#score').text('score: ' + score);
}
$('input').on('keyup', checkResults);
</script>
Bookmarks