Jump to content

Score Not Incrementing and errors


kadi

Recommended Posts

My Code Is about +1 score for every correct answer. Only a score of one is achieving for first question1 and when i type the correct answer for question2 score is not incrementing. My final score should be 2 since i have only two questions but whats happening in my code is that if i delete first answer 'yes' score is going to 4 and so on. Dont know where the error in my code is...
<div id="score" style="font: bolder 20px courier">score: 0</div><input type="text" id="question" /><input type="text" id="question1" /> <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');                score += 1;                 break;            } else {                $this.css('background-color', 'red');            }         }    }      if (score == 2) {        alert('Hi Ur Score is 2');    }      $('#score').text('score: ' + score); } $('input').on('keyup', checkResults);</script>
Link to comment
Share on other sites

You seem to be breaking out of the loop, meaning score will be a max of 1 per call to checkResults(), assuming you reset score to 0.

 

You are also only fetching the text input value once, which should be happening for each question in the loop.

 function checkResults() {score = 0;for (var k in answers) {var$this = $('#'+k),val = $this.val().toLowerCase();if (answers.hasOwnProperty(k)) {if (answers[k] === val) {$this.css('background-color', 'green');score++;} else {$this.css('background-color', 'red');}}}if (score == 2) {alert('Hi Ur Score is 2');}$('#score').text('score: ' + score);}
Edited by JamesB
  • Like 1
Link to comment
Share on other sites

 

You seem to be breaking out of the loop, meaning score will be a max of 1 per call to checkResults(), assuming you reset score to 0.

 

You are also only fetching the text input value once, which should be happening for each question in the loop.

 function checkResults() {score = 0;for (var k in answers) {var$this = $('#'+k),val = $this.val().toLowerCase();if (answers.hasOwnProperty(k)) {if (answers[k] === val) {$this.css('background-color', 'green');score++;} else {$this.css('background-color', 'red');}}}if (score == 2) {alert('Hi Ur Score is 2');}$('#score').text('score: ' + score);}

Sorry, Its working fine now. thanks

Edited by kadi
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...