Function in .html (function (x)) does not return html

I have an array containing 10 objects. Each line contains a question line, a line, correctAnswerand an object with 4 lines of answer:

const DB = [
{
  question: "some question",
  answers: ["a", "variety", "of", "choices"],
  correctAnswer: "variety"
}, ...

I have a function that captures the user's response through the radio button input and stores it in a variable:

function getFeedback(){
  return $("form input[type=radio]:checked")
           .closest('.css-answerscss-answers')
           .children('label')
           .text()
}

function feedbackPage(){
  $('.js-quizform-questions').on('click', '.js-button-next', function(event){
    event.preventDefault()
    let yourAnswer = getFeedback()
    $('.js-feedback-page').show().html(evalCorrectAnswer(DB))
  })
}

The last line then calls evalCorrectAnswer()with the DB parameter. I want to compare the response given by user ( yourAnswer) to correctAnswerin the database. All console logs work so that they return correct and identical responses. However, Correct/ Wronghtml is not sent back:

function evalCorrectAnswer(yourAnswer){
  console.log(yourAnswer)
  console.log(DB[0].correctAnswer)
  if (DB[0].correctAnswer === yourAnswer){
    `<p>Correct</p>`
  } else {
    `<p>Too bad</p>`
  }
}

What am I missing?

+4
source share
4 answers

You are missing instructions return, do it

function evalCorrectAnswer(yourAnswer){
  console.log(yourAnswer)
  console.log(DB[0].correctAnswer)
  return DB[0].correctAnswer === yourAnswer ? `<p>Correct</p>` : `<p>Too bad</p>`;
}
+4

return? if/else

:

if (DB[0].correctAnswer === yourAnswer){
    return `<p>Correct</p>`; 
} else {
    return `<p>Too bad</p>`;
}
+1

return !

...
return '<p>Correct</p>';
...

Also make sure that you use the correct quotation marks 'instead of `` `.

+1
source

Some languages ​​only allow you to return a value using an instruction. JavaScript is not one of these languages. To return the result of a function, you need to explicitly use the operator return.

Minimal code fix:

 function evalCorrectAnswer(yourAnswer){
   console.log(yourAnswer)
   console.log(DB[0].correctAnswer)
 if (DB[0].correctAnswer === yourAnswer){
   return '<p>Correct</p>'
 } else {
   return '<p>Too bad</p>'
 }
}
0
source

Source: https://habr.com/ru/post/1696317/


All Articles