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

10
  • 1
    See this question: stackoverflow.com/questions/20354920/… Maybe this helps you! Commented May 8, 2020 at 9: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"; " Commented May 8, 2020 at 9: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 Commented May 8, 2020 at 9:41
  • 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. Commented May 8, 2020 at 10:01
  • 1
    @PavanaSriPalepu You have to open a new StackOverflow question for this. Commented May 20, 2020 at 13:03

2 Answers 2

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;
  }
}
Sign up to request clarification or add additional context in comments.

6 Comments

can u please explain how to restrict the user to select other option when user selected the one option already how to write code?
You can disable the rest of the radio buttons for the question by adding the disabled attribute to it.
how can u show the code I want that code can u replace the code with disabled option sonu please help me !!!
Okay! I'll update my answer to have this part as well.
Actually ur dislaying the text to change into the green and red right but I want the background color need to change as per the Philip code !!?
|
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();" />

1 Comment

Comments are not for extended discussion; this conversation has been moved to chat.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.