I am facing an issue with my if statement not functioning properly when verifying a radio input

Trying to validate radio input to confirm if it's the correct answer, but encountering an issue where it skips the line

if (answer == allQuestions[q].correctAnswer)
.

Here is the complete code: https://jsfiddle.net/alcatel/sopfmevh/1/

for (let k = 0; k < answers.length; k++) {
  if (answers[k].checked) {
    answer = answers[k].value;
  }
}

// IT SKIPS THIS LINE !!
if (answer == allQuestions[q].correctAnswer) { // IT SKIPS THIS LINE!!
  alert("correct");
}

q++;
    
populate();

Answer №1

I believe the correct syntax for your If statement would be:

if(answer === allQuestions[q].choices[allQuestions[q].correctAnswer]) {
        alert("You got it right!");
    }

Tweaked this a bit and tested - seems to be functioning well now

Answer №2

One way to compare is by utilizing the element's index within the array.

if(allQuestions[q].choices.indexOf(answer) == allQuestions[q].correctAnswer) {
    alert("you got it right!");
}

Answer №3

because I made it happen...

const allQuestions = 
        [ { question     : 'What is the capital of France?'
          , choices      : [ 'Berlin', 'Paris', 'London' ] 
          , correctAnswer: 1
          } 
        , { question     : 'What is the tallest mountain in the world?'
          , choices      : [ 'Mount Everest', 'K2', 'Mauna Kea' ] 
          , correctAnswer: 0
          } 
        , { question     : 'Which planet is known as the Red Planet?'
          , choices      : [ 'Venus', 'Mars', 'Jupiter' ] 
          , correctAnswer: 1
          } 
        ] 
function* qList(arr) { for (let q of arr) yield q }

const libQuestion  = document.querySelector('h1')
  ,   formReplies  = document.getElementById('list')
  ,   btNext       = document.querySelector('button')
  ,   DomParser    = new DOMParser()
  ,   qListRead    = qList( allQuestions )
  ,   score        = { correct: 0, count:0 }
  ;
var currentAnswer = ''
  ;
function setNewQuestion()
  {
  formReplies.innerHTML = ''

  let newQuestion = qListRead.next()
  if (!newQuestion.done)
    {
    libQuestion.textContent = newQuestion.value.question
    currentAnswer           = newQuestion.value.correctAnswer
    ++score.count
    newQuestion.value.choices.forEach((choice,indx)=>
      {
      let line = `<label><input type="radio" name="answer" value="${indx}">${ choice}</label>`
        , inLn = (DomParser.parseFromString( line, 'text/html')).body.firstChild
        ;
      formReplies.appendChild(inLn)
      })
    }
  else
    {
    libQuestion.textContent = ` Score = ${score.correct} / ${score.count}`
    btNext.disabled         = true
    }
  }
setNewQuestion()
btNext.onclick=()=>
  {
  if (formReplies.answer.value)
    {
    score.correct += ( currentAnswer == formReplies.answer.value )
    setNewQuestion()
    }
  }
<h1></h1>
<p></p>
<form id="list"></form>
<br>
<button>next</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for converting a window to a PDF file rather than an XPS file

Whenever I attempt to print the contents of my HTML page using window.print(), it always creates an XPS file. However, what I really need is for it to generate a PDF file instead. Any assistance would be greatly appreciated. Thank you! ...

What is the reason behind TypeScript's decision not to raise an error in case of a mismatched function argument type?

Here's a simple illustration to showcase my point: type Info = { id: number; } type ImportantInfo = { id: number; value: 5; } type Task = (data: Info) => void; const task: Task = data => null; const data: ImportantInfo = { i ...

JavaScript Array join() method returns an empty string

As a beginner in the world of javascript, I am just starting to dip my toes into it. In the past, I have used join() without any issues, but now I am facing a problem where this join is returning an empty string. Upon inspecting myArray, the data seems t ...

PHP question about maintaining data continuously

So, I've created this interesting JavaScript 'thing' with the help of jQuery and AJAX. The main concept behind it is that a div can be edited (contenteditable=true), which sparked the idea to develop a chatroom-like feature. It's pretty ...

The combination of setInterval() and if(confirm()) is not possible in pure JavaScript

One day, I encountered a simple if(confirm()) condition like this: if(confirm('Some question')) { agreed_function(); } else { cancel_function(); } function agreed_function() { console.log('OK'); } function cancel_function( ...

Angular foreach method encounters a syntax issue

When I use the getTotal.getValues() function to make a server call that returns values like "one", "two", "three" up to "nine", I am able to print them using console.log(res). However, I am facing an issue where I cannot push these returned values into t ...

Instructions for creating a slush machine

Today, I tried to create a slush generator but ran into some issues. Even after following tutorials online and double-checking my work, the generator doesn't seem to be functioning properly. If anyone can identify what I might have done wrong, please ...

"Production environment encounters issues with react helper imports, whereas development environment has no trouble with

I have a JavaScript file named "globalHelper.js" which looks like this: exports.myMethod = (data) => { // method implementation here } exports.myOtherMethod = () => { ... } and so forth... When I want to use my Helper in other files, I import it ...

Best practices for building an Ember frontend and Node backend application

I'm currently working on a project that involves an ember frontend and a node backend. Within my ember-cli app, I've configured the .ember-cli file to proxy requests to node like this: { "proxy": "http://localhost:3000" } I've had to es ...

Error: protractor encountered an unexpected issue

Currently, I am following this tutorial I went through all the steps mentioned in the tutorial except for what was suggested in this post instead of npm install -g protractor I opted for npm install -g protractor --no-optional So far, I have succe ...

Sending JSON data from PHP to JavaScript using Ajax

Currently, I am attempting to transfer a JSON object from a PHP script to a JavaScript file using Ajax. The code I have been using successfully for a single string is now being modified to accommodate multiple strings within a JSON object. Below are snippe ...

The PHP script encountered an issue with the HTTP response code while processing the AJAX contact form, specifically

Struggling to make this contact form function properly, I've tried to follow the example provided at . Unfortunately, all my efforts lead to a fatal error: "Call to undefined function http_response_code() in /hermes/bosoraweb183/b1669/ipg.tenkakletcom ...

Verification of javascript for an unpredictable image generator script

When running the W3C Validation tool, an error is returned stating 'img not acceptable here.' Any suggestions on how to resolve this issue? <script type="text/javascript" language="JavaScript"> NumberOfImagesToRotate = 9; FirstPart = &ap ...

Here are some steps for generating a non-integer random number that is not in the format of 1.2321312312

I am looking to create random numbers that are not integers, for example 2.45, 2.69, 4.52, with a maximum of two decimal places. Currently, the generated number includes many decimal places like 2.213123123123 but I would like it to be displayed as 2.21. ...

Using Mongoose, Express, and Node.js to send a server variable to an HTML page

I've encountered an issue while attempting to transfer a variable from my server.js file to HTML. Despite successfully passing the variable to another EJS file on a different route, I can't seem to display it within this specific EJS file. Strang ...

Hold on for the useState object to contain a value

Created a custom hook that fetches the user's location and determines the nearest marker on a map based on that information. Initially, it returns the default value of useState. The response looks like this: { coordinates: { lat: '', lng: ...

The test suite encountered an error (EBUSY: resource busy or locked) and unfortunately failed to run at Nx version 14.5.10 and Jest version 27.5.1. It seems there was an

I have recently upgraded my NX Monorepo from version 13 to 14, and everything seems to be working fine except for the Jest migration. I keep encountering this error even after trying various solutions like clearing the cache, deleting node_modules, and rei ...

Select an item from the options available

Looking to automatically select a specific item from a combobox upon clicking a button on my webpage. The page includes both PHP and JavaScript code for this functionality. Currently, I have a JavaScript function triggered by the "onclick" event of the bu ...

How to refresh an array in Angular 4 after inserting a new element using splice method?

I have a Angular list displayed in a table, and I need to insert an element at a specific position. I have tried using the following code: array.splice(index, 0, element); While everything seems fine in the console with the element being added at the corr ...

Difficulty surfaced in the React project following relocation to a different device

I'm new to using React and webpack with babel loader in my app. My project was running smoothly until I changed machines. I copied all the files except for node_modules (which I installed with npm install). Now, when I try to run or build the projec ...