0

I am creating the quiz app using JavaScript . I want to change the color of the input button when the user click on that as per the answer. if the answer is true then need to change the color to red and if the answer is wrong then the color need to change to red . Need to select only one option for every question. If the user selected one option it need to highlight green other wise red . if red then it need to highlight the green . Should not give the other chance to user to click on the options everytime to see which option is correct.

Html :

  <label class="option"><input type="radio"  name="option" value="1" onclick="check()"/> <span id="opt1"></span></label>
    <label class="option"><input type="radio" name="option" value="2" onclick="check()" /> <span id="opt2"></span></label>
    <label class="option"><input type="radio" name="option" value="3" onclick="check()"/> <span id="opt3"></span></label>
    <label class="option"><input type="radio" name="option" value="4" onclick="check()"/> <span id="opt4"></span></label>
<button id="nextButton" class="next-btn" onclick="loadNextQuestion();">Next </button>

**Js onclick function **

    var questions = [];
  $.ajax({
    url: 'http://127.0.0.1:8000/api/?format=json',
    type:'GET',
    async:true,
    dataType: "json",
    success: function(data)
     {
        questions = data ;
        loadQuestion();

     }
  });




function loadQuestion(){
    //questionIndex = 0
    var questionEl = document.getElementById("question");
    var opt1 = document.getElementById("opt1");
    var opt2 = document.getElementById("opt2");
    var opt3 = document.getElementById("opt3");
    var opt4 = document.getElementById("opt4");

    questionEl.innerHTML = (currentQuestion + 1) + '. '+ questions[currentQuestion].question;
    opt1.innerHTML = questions[currentQuestion].option1;
    opt2.innerHTML = questions[currentQuestion].option2;
    opt3.innerHTML = questions[currentQuestion].option3;
    opt4.innerHTML = questions[currentQuestion].option4;
  }


  var currentQuestion = 0;
  var score = 0;
  var totQuestions = 8;


function loadNextQuestion() {
  resetColor();
  var selectedOption = document.querySelector('input[type=radio]:checked');
    if(!selectedOption){
    alert('Please select your answer!' );
        return;
  }
    var answer = selectedOption.value;
    if(questions[currentQuestion].correct_answer == answer){
        score += 10;
  }

    selectedOption.checked = false;
  currentQuestion++;

  var nextButton =document.getElementById('nextButton');
    if(currentQuestion == totQuestions - 1){
        nextButton.innerHTML = 'Finish';
  }

  var container = document.getElementById('quizContainer');
  var resultCont = document.getElementById('result');

    if(currentQuestion == totQuestions){
        container.style.display = 'none';
        resultCont.style.display = '';
        resultCont.textContent = 'Your Score: ' + score;
        return;
    }
    loadQuestion(currentQuestion);
}

loadQuestion(currentQuestion);
      function check()
    {
      var selectedOption = document.querySelector('input[type=radio]:checked');
      var answer = selectedOption.value;
      if(questions[currentQuestion].correct_answer == answer)
      {
        document.getElementsByName('option').style.color="green";         
      }
      else{
        document.getElementsByName('option').style.color="red";         

          }
    }

I just wrote document.getElementsByName('option').style.color="red"; ** but not worked it is showing the error " **Uncaught TypeError: Cannot set property 'color' of undefined

1.What is the wrong with that line. can u please help me guys.enter image description here

This is the json object. enter image description here

  • 1
    See this question: https://stackoverflow.com/questions/20354920/how-to-change-the-style-of-a-radio-button-with-javascript-when-clicked Maybe this helps you! – Laurens May 08 '20 at 09:24
  • yes I saw before but it is using the for loop and input[radio] so it is also getting error once say what I need to keep / change in this line "document.getElementsByName('option').style.color="red"; " – Pavana Sri Palepu May 08 '20 at 09:30
  • 1
    the return of document.getElementsByName('option') will be an array .... you neeed to specify the index like follow document.getElementsByName('option')[0].style.color – Deepu May 08 '20 at 09:41
  • No again it showing the error like color undefined !!. Please once say me cleary deepu please. – Pavana Sri Palepu May 08 '20 at 09:46
  • 1
    `document.getElementsByName('option')` returns an array not an element. Thus you would need to specify an index like so `document.getElementsByName('option')[index]` to access a specific element in the array. It says undefined because arrays do no have style properties. – Phillip Schulze May 08 '20 at 10:01
  • okay I got ur point thank you :-) – Pavana Sri Palepu May 08 '20 at 10:05
  • Yes worked Philip I just sent u the message in the chat room but u did not saw the message I think so. Thank you so much Philip. It means a lot to me :- ) – Pavana Sri Palepu May 09 '20 at 13:06
  • @PhillipSchulze I want to display only next button after clicking on one of the radio button! how to display only on clicking on the button. can u please help me I just tried show and hide () but not working ? – Pavana Sri Palepu May 20 '20 at 09:29
  • 1
    @PavanaSriPalepu You have to open a new StackOverflow question for this. – Phillip Schulze May 20 '20 at 13:03
  • @PhillipSchulze I asked the question about the JavaScript see this link once:https://stackoverflow.com/questions/61913123/how-to-display-timer-using-javascript-properly. – Pavana Sri Palepu May 22 '20 at 03:12

2 Answers2

1

The problem is with document.getElementsByName('option').style.color as you are trying to get element by tag name, which returns array of all matching elements and there is no element named as option in the html. Assuming you wants to show if the selected answer is right or wrong. If right, show green color for the text or red in case of the wrong answer.

function check()
{
  var selectedOption = document.querySelector('input[type=radio]:checked');
  var answer = selectedOption.value;
  var parentDiv = selectedOption.parentNode;
  if(questions[currentQuestion].correct_answer == answer)
  {
    parentDiv.style.color="green";         
  } else{
    parentDiv.style.color="red";         
  }
}

Another easy way would be to attach the id element to the label and pass that id to the check method

<label class="option" id="option1">
   <input type="radio"  name="option" value="1" onclick="check(1, 'option1')"/> 
   <span id="opt1"></span>
</label>
<label class="option" id="option2">
  <input type="radio" name="option" value="2" onclick="check(2, 'option2')" /> 
  <span id="opt2"></span>
</label>
<label class="option" id="option3">
  <input type="radio" name="option" value="3" onclick="check(3, 'option3')"/> 
  <span id="opt3"></span>
</label>
<label class="option" id="option4">
  <input type="radio" name="option" value="4" onclick="check(4, 'option4')"/> 
  <span id="opt4"></span>
</label>

JS:

function check(answer, divId)
{
  var parentDiv = document.getElementById(divId);
  if(questions[currentQuestion].correct_answer == answer)
  {
    parentDiv.style.color = "green";         
  } else{
    parentDiv.style.color = "red";         
  }
}

Update, disable rest of the radio buttons Wrap all the lables in a div.

<div>
<label class="option" id="option1">
   <input type="radio"  name="option" value="1" onclick="check(1, 'option1')"/> 
   <span id="opt1"></span>
</label>
<label class="option" id="option2">
  <input type="radio" name="option" value="2" onclick="check(2, 'option2')" /> 
  <span id="opt2"></span>
</label>
<label class="option" id="option3">
  <input type="radio" name="option" value="3" onclick="check(3, 'option3')"/> 
  <span id="opt3"></span>
</label>
<label class="option" id="option4">
  <input type="radio" name="option" value="4" onclick="check(4, 'option4')"/> 
  <span id="opt4"></span>
</label>
</div>
function check(answer, divId)
{
  var parentDiv = document.getElementById(divId);
  if(questions[currentQuestion].correct_answer == answer)
  {
    parentDiv.style.color = "green";         
  } else{
    parentDiv.style.color = "red";         
  }
  // additional codes to disable the other options.
  const options = parentDiv.parentNode.querySelectorAll("input[type=radio]");
  for(var i = 0; i < options.length; i++){
    options[i].disabled = true;
  }
}
Sonu Bamniya
  • 1,095
  • 1
  • 13
  • 29
1

Add the check function to each radio element's onchange event and then pass that radio element as the argument:

<label class="option"><input type="radio" name="option" value="1" 
onchange="check(this);" /> <span id="opt1"></span></label>

Then change the javascript function accordingly:

function check(radio) {
resetColor();
  if (radio.checked) {
    if (questions[currentQuestion].correct_answer == radio.value) {
      radio.parentNode.style.backgroundColor = "green";
    } else {
      radio.parentNode.style.backgroundColor = "red";
    }
  } else {
    radio.parentNode.style.backgroundColor = "white";
  }
}

function resetColor() {
  let options = document.querySelectorAll("input[name=option]");
  for (let i = 0; i < options.length; ++i) {
    options[i].parentNode.style.background = "none"
  }
}

Here is an example I made that demonstrates what you are trying to do:

var CurrentQuestion = 1;
var Answers = [3, 1, 2, 4, 3];
var AnswerStrings = ["AAA", "BBB", "CCC", "DDD"];
var done = false;

function check(radio) {
  resetColor();
  if (radio.checked) {
    if (Answers[CurrentQuestion - 1] !== parseInt(radio.value)) {
      radio.parentNode.style.backgroundColor = "red";
      //document.getElementById("answer").innerHTML = AnswerStrings[Answers[CurrentQuestion]];
      //document.getElementById("answer").style.border = "1px solid red";
    }
    showCorrect();
  } else {
    radio.parentNode.style.backgroundColor = "white";
  }
}

function showCorrect() {
  let options = document.querySelectorAll("input[name=option]");
  for (let i = 0; i < options.length; ++i) {
    if (parseInt(options[i].value) === Answers[CurrentQuestion - 1]) {
      options[i].parentNode.style.backgroundColor = "green";
    }
    options[i].setAttribute("disabled", "true");
  }
}

function resetColor() {
  let options = document.querySelectorAll("input[name=option]");
  for (let i = 0; i < options.length; ++i) {
    options[i].parentNode.style.background = "none"
  }
}

function resetQuestion() {
  document.getElementById("answer").innerHTML = "";
  document.getElementById("answer").style.border = "none";
  let options = document.querySelectorAll("input[name=option]");
  for (let i = 0; i < options.length; ++i) {
    options[i].removeAttribute("disabled");
    options[i].parentNode.style.background = "none"
    options[i].checked = false;
  }
}

function next() {
  resetQuestion();
  CurrentQuestion++;
  if (CurrentQuestion > Answers.length) CurrentQuestion = Answers.length;
  document.getElementById("Qn").innerHTML = " " + CurrentQuestion;
}

function prev() {
  resetQuestion();
  CurrentQuestion--;
  if (CurrentQuestion < 1) CurrentQuestion = 1;
  document.getElementById("Qn").innerHTML = " " + CurrentQuestion;
}

document.getElementById("Qn").innerHTML = " " + CurrentQuestion;
body {
  background-color: lightblue;
}

label{
  user-select: none;
}
<h1>Question<span id="Qn"></span></h1>

<label class="option"><input type="radio" name="option" value="1" onchange="check(this);" /> <span id="opt1">AAA</span></label>
<label class="option"><input type="radio" name="option" value="2" onchange="check(this);" /> <span id="opt2"></span>BBB</label>
<label class="option"><input type="radio" name="option" value="3" onchange="check(this);" /> <span id="opt3">CCC</span></label>
<label class="option"><input type="radio" name="option" value="4" onchange="check(this);" /> <span id="opt4">DDD</span></label>
<br/>
<p id="answer">
  <p>
    <br/>
    <input type="button" value="Prev" onclick="prev();" />
    <input type="button" value="Next" onclick="next();" />
Phillip Schulze
  • 118
  • 2
  • 8
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/213423/discussion-on-answer-by-phillip-schulze-how-to-change-the-color-of-the-particula). – Samuel Liew May 08 '20 at 13:44