'How can I fix scoring for multiple-answer questions in my Angular quiz app?

For the multiple-answer questions, ALL of the correct answers should be selected in order for the score to increase, not just one correct answer. If one correct answer is selected and then the next answer is marked as incorrect, the score still increases by 1; it should increase only when all of the correct answers are given... If one incorrect answer is given and then all correct answers, then the score should also increase OR if a correct answer, followed by an incorrect and then a correct answer, the score should increase. Also the single-answer questions should increase score as expected. Please could you help to fix this issue. See my app here: https://stackblitz.com/edit/angular-10-quiz-app

Current code snippet for increasing score (in src -> app -> containers -> quiz -> quiz.component.ts -> checkIfAnsweredCorrectly()):

checkIfAnsweredCorrectly() {
  if (this.question) {
    const correctAnswerFound = this.answers.find((answer) => {
      return this.question.options &&
        this.question.options[answer] &&
        this.question.options[answer]['selected'] &&
        this.question.options[answer]['correct'];
    });

    const answers = this.answers && this.answers.length > 0 ? this.answers.map((answer) => answer + 1) : [];
    this.quizService.userAnswers.push(this.answers && this.answers.length > 0 ? answers : this.answers);

    if (correctAnswerFound > -1 && 
        answers.length === this.quizService.numberOfCorrectAnswers) {
      this.sendCorrectCountToQuizService(this.correctCount + 1);
    }
  }
}


Solution 1:[1]

@integral100x

You need to change your checkIfAnsweredCorrectly method logic in DependencyInjectionQuizComponent.

You need to check your correctAnswerFound is greater than -1 because if your array has find the element in position 0. The If loop has exits due to value 0. So that, I changed to check greater than -1.

if (correctAnswerFound > -1) {
        this.sendCorrectCountToQuizService(this.correctCount + 1);
}

instead of

if (correctAnswerFound) {
    this.sendCorrectCountToQuizService(this.correctCount + 1);
}

Thanks

Solution 2:[2]

the solution is very simple. separate your "right/wrong" logic from your "next button" logic.

you shouldn't have anything like this:

if (!incorrectAnswerFound) {
  this.sendCorrectCountToQuizService(this.correctCount + 1);
}

instead your functions should look like this:

advanceToNextQuestion() { ... }

and

addUpScores() { ... }

don't try to combine logic into a single function. that's why your app is not working.

Solution 3:[3]

how i can calculate suppose user is selected question 1 option (a.) then multiplied by 4,  if they select (b.) then multiplied by 3, if they select (c.) then multiplied by 2,if they select (d.) then multiplied by 1, i Dont want correct answer.

quiz.html
=========

 <template>
<lightning-card title="BMI Quiz App">
<div class="slds-m-around_medium">
<template if:true={isSubmitted}>
<!-- <div class={isScoredFull}> You Health Score is {correctAnswer} Out of {questions.length} </div> -->
<div class={isScoredFull}> You Health Score is {correctAnswer}</div>
</template>
<template if:true={enablesmile1}>
<img src={GreenImage}  height="30px"
width="35px">
</template>
<template if:true={enablesmile2}>
    <img src={YellowImage}  height="30px"
    width="35px">
</template>
<template if:true={enablesmile3}>
<img src={RedImage}  height="30px"
width="35px">
</template>
<form>
<template for:each={questions} for:item="quiz">
<div key={quiz.id} class="slds-m-bottom_medium">

<div><strong>{quiz.id} :- {quiz.ques}</strong></div>
<div class="slds-grid slds-grid_vertical slds-m-bottom_x-small">

<div class="slds-col">
<input type="radio" name={quiz.id} value="a" onchange={changeHandler}/>
{quiz.answers.a}
</div>

<div class="slds-col">
<input type="radio" name={quiz.id} value="b" onchange={changeHandler}/>
{quiz.answers.b}
</div>

<div class="slds-col">
<input type="radio" name={quiz.id} value="c"  onchange={changeHandler}/>
{quiz.answers.c}
</div>

<div class="slds-col">
<input type="radio" name={quiz.id} value="d" onchange={changeHandler} />
{quiz.answers.d}
</div>
</div>
</div>
</template>

<div class="slds-grid slds-grid_align-center">
<lightning-button variant="brand" 
type="submit" label="Submit" 
title="Submit Quiz" 
class="slds-col slds-m-around_medium" 
disabled={allNotSelected}
onclick={submitHandler}>
</lightning-button>

<lightning-button variant="brand" 
type="reset" label="Reset" 
title="Reset Quiz" 
class="slds-col slds-m-around_medium" 
onclick={resetHandler}>
</lightning-button>
</div>

</form>
</div>
</lightning-card>
</template>

quiz.js
========

    import { LightningElement } from 'lwc';
import Green_Image from '@salesforce/resourceUrl/GreenImage';
import Yellow_Image from '@salesforce/resourceUrl/YellowImage';
import Red_Image from '@salesforce/resourceUrl/RedImage';

export default class BmiQuiz extends LightningElement {
     GreenImage=Green_Image;
     YellowImage=Yellow_Image;
     RedImage=Red_Image;

selected={}
correctAnswer=0
isSubmitted=false
enablesmile1=false;
enablesmile2=false;
enablesmile3=false;
optionvalue;

questions=[
{

    id:'1',
    ques:'I have felt cheerful and in good spirits  ?',
    answers:{
    a:'All of the time.',
    b:'Most of the time.',
    c:'Half of the time.',
    d:'Some of the time.'
},
    correctAnswer:'b'
},

{

    id:'2',
    ques:'I have felt calm and relaxed  ?',
    answers:{
        a:'All of the time.',
        b:'Most of the time.',
        c:'half of the time.',
        d:'Some of the time.'
    },
        correctAnswer:'b'
},

{
    id:'3',
    ques:'I have felt active and vigorous ?',
    answers:{
        a:'All of the time.',
        b:'Most of the time.',
        c:'half of the time.',
        d:'Some of the time.'
    },
        correctAnswer:'c'
},


{
    id:'4',
    ques:'I woke up feeling fresh and rested ?',
    answers:{
        a:'All of the time.',
        b:'Most of the time.',
        c:'Half of the time.',
        d:'Some of the time.'
    },
        correctAnswer:'d'
    },

{

    id:'5',
    ques:' My daily life has been filled with things that interest me ?',
    answers:{
        a:'All of the time.',
        b:'Most of the time.',
        c:'half of the time.',
        d:'Some of the time.'
    },
        correctAnswer:'b'
}]

get allNotSelected(){
    return !(Object.keys(this.selected).length===this.questions.length)
}

get isScoredFull(){
    return `slds-text-heading_large ${this.questions.length===this.correctAnswer?
        'slds-text-color_success':'slds-text-color_error'
    }`
}

changeHandler(event){
console.log("value",event.target.value)
console.log("name",event.target.name)
const{name,value}=event.target
this.selected={...this.selected,[name]:value}
 this.optionvalue=this.questions.filter(item=>this.selected[item.value])
console.log('optionvalue'+this.optionvalue)
}

submitHandler(event){
  event.preventDefault()
  let correct=  this.questions.filter(item=>this.selected[item.id]===item.correctAnswer)
  this.correctAnswer=correct.length
  this.isSubmitted=true
  console.log('correctAnswer',this.correctAnswer)
 

if(this.correctAnswer ==4){
    this.enablesmile1=true;
    this.enablesmile2=false;
    this.enablesmile3=false;
 }
 else if( this.correctAnswer==3 ){
   this.enablesmile2=true;
   this.enablesmile3=false;
   this.enablesmile1=false;
  }
 else if( this.correctAnswer==2 ){
    this.enablesmile3=true;
    this.enablesmile2=false;
    this.enablesmile1=false;


 }

}

resetHandler(){
    this.selected={}
    this.correctAnswer=0
    this.isSubmitted=false

}

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arunkumar Ramasamy
Solution 2 Rick
Solution 3 user18920646