change label text of all radio button in quiz as red and green

Below is the code of a sample radio button quiz where multiple radio buttons are provided. Correct answers and wrong answers are defined in the code. User may check any answer or keep all blank. If user checks any radio button and finally clicks "Grade Me" button, label text of radio button of any wrong answers checked by the user shall appear as red and at the same time correct answer of that particular question shall appear in green (This will help the user know which question he answered wrong and what is its correct answer). I have tried several steps and searched many forums and failed. I think it will be really simple.

Example:

var numQues = 3;
var numChoi = 3;
var answers = new Array(3);
answers[0] = "doesn't like";
answers[1] = "don't come";
answers[2] = "come";
var wrong = new Array(3);
wrong[0] = "don't like";
wrong[1] = "doesn't come";
wrong[2] = "comes";
var wrong1 = new Array(3);
wrong1[0] = "doesn't likes";
wrong1[1] = "doesn't comes";
wrong1[2] = "coming";

function getScore(form) {
  var score = 0;
  var currElt;
  var currSelection;
  for (i = 0; i < numQues; i++) {
    currElt = i * numChoi;
    answered = false;
    for (j = 0; j < numChoi; j++) {
      currSelection = form.elements[currElt + j];
      if (currSelection.checked) {
        answered = true;
        if (currSelection.value == answers[i]) {
          score += 3;
          break;
        }
        if (currSelection.value == wrong[i]) {
          score -= 1;
          break;
        }
        if (currSelection.value == wrong1[i]) {
          score -= 1;
          break;
        }
      }
    }
  }
  var scoreper = Math.round(score * 100 / 9);
  form.percentage.value = scoreper + "%";
  form.mark.value = score;
}
<title>Quiz Questions And Answers</title>
<center>
  <h1>Quiz Questions</h1>
</center>
<p>
  <form name="quiz">
    <p>
      <b><br>1. He -------------------- it.<br></b>
      <label><input type="radio" name="q1" value="don't like">don't like</label><br>
      <label><input type="radio" name="q1" value="doesn't like">doesn't like</label><br>
      <label><input type="radio" name="q1" value="doesn't likes">doesn't likes</label><br>
      <p><b>
        <hr>
        <br>2. They -------------------- here very often.<br></b>
        <label><input type="radio" name="q2" value="don't come">don't come</label><br>
        <label><input type="radio" name="q2" value="doesn't come">doesn't come</label><br>
        <label><input type="radio" name="q2" value="doesn't comes">doesn't comes</label><br>
        <p><b>
        <hr>
        <br>3. John and Mary -------------------- twice a week.<br></b>
          <label><input type="radio" name="q3" value="come">come</label><br>
          <label><input type="radio" name="q3" value="comes">comes</label><br>
          <label><input type="radio" name="q3" value="coming">coming</label>
          <br>
          <p><b>
        <hr>
        <p><b>
        <input type="button"value="Grade Me"onClick="getScore(this.form);">
        <input type="reset" value="Clear"><p>
        Number of score out of 15 = <input type= text size 15 name= "mark">
        Score in percentage = <input type=text size=15 name="percentage"><br>
        </form>
        <p>
        <form method="post" name="Form" onsubmit="" action="">
        </form>

Answers:

Answer

Here is a rewrite of your code. I fixed the illegal HTML and used best practices with event listeners, querySelectors and CSS

Please study the code and see if you understand. I can add more comments if needed

var answers = ["doesn't like","don't come","come"];
var rads, quiz; // need to be set after load
window.addEventListener("load",function() { // when page loads
  quiz = document.getElementById("quiz");
  rads = quiz.querySelectorAll("input[type=radio]"); // all radios in the quiz
  document.getElementById("scoreButton").addEventListener("click",function(e) { // on click of scoreme
    var score = 0;
    for (var i=0;i<rads.length;i++) { // loop over all radios in the form
      var rad = rads[i];
      var idx = rad.name.substring(1)-1; //remove the q from the name - JS arrays start at 0
      var checked = rad.checked;
      var correct = rad.value==answers[idx];
      
      if (correct) {
        rad.closest("label").classList.toggle("correct");
        if (checked) score +=3;
      }  
      else if (checked) {
        score--;
        rad.closest("label").classList.toggle("error")
      }  
    }
    var scoreper = Math.round(score * 100 / rads.length);
    document.querySelector("#percentage").innerHTML = scoreper + "%";
    quiz.mark.value = score;
  });  
});
.correct {
  color: green
}

.error {
  color: red
}
<title>Quiz Questions And Answers</title>
<div class="header">
  <h1>Quiz Questions</h1>
</div>
<form id="quiz">
  <div class="questions">
    <p>
      <b>1. He -------------------- it.</b><br/>
      <label><input type="radio" name="q1" value="don't like" />don't like</label><br/>
      <label><input type="radio" name="q1" value="doesn't like" />doesn't like</label><br/>
      <label><input type="radio" name="q1" value="doesn't likes" />doesn't likes</label>
    </p>
    <hr>
    <p><b>2. They -------------------- here very often.</b><br/>
      <label><input type="radio" name="q2" value="don't come">don't come</label><br/>
      <label><input type="radio" name="q2" value="doesn't come">doesn't come</label><br/>
      <label><input type="radio" name="q2" value="doesn't comes">doesn't comes</label>
    </p>
    <hr>
    <p><b>3. John and Mary -------------------- twice a week.</b><br/>
      <label><input type="radio" name="q3" value="come">come</label><br/>
      <label><input type="radio" name="q3" value="comes">comes</label><br/>
      <label><input type="radio" name="q3" value="coming">coming</label><br/>
    </p>
    <hr>
    <p>
      <input type="button" value="Grade Me" id="scoreButton">
      <input type="reset" value="Clear"><br/> 
      Number of score out of 15 = <input type="text" size="15" id="mark"> 
      Score in percentage = <span id="percentage"></span>
    <p>
  </div>
</form>

Answer

In your getScore function, when you find out that a certain element has a correct answer selected (whichever var is the label - unless you are using a custom radio button which I would recommend since changing the background of the label element would simply highlight the words), you can give it a new class using JS.

currSelection.classList.add("correct");

or

currSelection.classList.add("incorrect");

Then in your CSS file you can have rules saying

.correct { background: green !important; }

.incorrect { background: red !important; }

Answer

WoW!....Close....Thanks for support. But still all the wrong answers are showing red color. This will let the user know which question he answered wrong. That part is Okay. But once the wrong answers are marked with red(I mean only the wrongly selected radio button choice texts and not the entire question and answer choices

the correct answer of that wrong attempt to be shown in green to enlighten the user. And the sad part is that I again failed with the CSS thing. I wanted to create a quiz in blog and added custom CSS with conditional tag in html of blogger post.....Not Working. However, I will add the modified code here so that you get a clear picture if I am doing rightly as you said.(How and where to add the CSS rules inside this code(if that is what you mean))

var answers = ["doesn't like", "don't come", "come"];
var rads, quiz; // need to be set after load
window.addEventListener("load", function() { // when page loads
  quiz = document.getElementById("quiz");
  rads = quiz.querySelectorAll("input[type=radio]"); // all radios in the quiz
  document.getElementById("scoreButton").addEventListener("click", function(e) { // on submit
    var score = 0;
    var checked = quiz.querySelectorAll("input[type=radio]:checked"); // all checked radios
    for (var i = 0; i < checked.length; i++) { // loop over all checked radios in the form
      var idx = checked[i].name.substring(1) - 1; //remove the q from the name - JS arrays start at 0
      var correct = checked[i].value == answers[idx];
      checked[i].closest("p").classList.toggle("error", !correct)
      checked[i].closest("p").classList.toggle("correct", correct)
      score += correct ? 3 : -1; // this is called a ternary
    }
    var scoreper = Math.round(score * 100 / rads.length);
    document.querySelector("#percentage").innerHTML = scoreper + "%";
    quiz.mark.value = score;
  });
});
<!DOCTYPE HTML>
<html>

<body>
  <title>Quiz Questions And Answers</title>
  <div class="header">
    <h1>Quiz Questions</h1>
  </div>
  <form id="quiz">
    <div class="questions">
      <p>
        <b>1. He -------------------- it.</b><br/>
        <label><input type="radio" name="q1" value="don't like" />don't like</label><br/>
        <label><input type="radio" name="q1" value="doesn't https://stackoverflow.com/questions/53818896/change-label-text-of-all-radio-button-in-quiz-as-red-and-green/59801712#like" />doesn't like</label><br/>
        <label><input type="radio" name="q1" value="doesn't likes" />doesn't likes</label>
      </p>
      <hr>
      <p><b>2. They -------------------- here very often.</b><br/>
        <label><input type="radio" name="q2" value="don't come">don't come</label><br/>
        <label><input type="radio" name="q2" value="doesn't come">doesn't come</label><br/>
        <label><input type="radio" name="q2" value="doesn't comes">doesn't comes</label>
      </p>
      <hr>
      <p><b>3. John and Mary -------------------- twice a week.</b><br/>
        <label><input type="radio" name="q3" value="come">come</label><br/>
        <label><input type="radio" name="q3" value="comes">comes</label><br/>
        <label><input type="radio" name="q3" value="coming">coming</label><br/>
      </p>
      <hr>
      <p>
        <input type="button" value="Grade Me" id="scoreButton">
        <input type="reset" value="Clear"><br/> Number of score out of 15 = <input type="text" size="15" id="mark"> Score in percentage = <span id="percentage"></span>
        <p>
    </div>
  </form>

</body>

</html>

Answer

You can try this:

    <!DOCTYPE html>
<html>
    <head>
<script>

function myFunction() {
    var coffee = document.forms[0];
    var txt = "";
    var i;
    for (i = 0; i < coffee.length; i++) {
        if (coffee[i].checked) {
            document.getElementById("score"+i).style.color = "green";
            document.getElementById("order").value = "You Clicked Option " + i;
        }

}                                        }
</script>

    </head>
<body>
  <div id="score1" style="font-size: 50px">1</div>
  <div id="score2" style="font-size: 50px">2</div>
  <div id="score3" style="font-size: 50px">3</div>
  <div id="score4" style="font-size: 50px">4</div>
**<form action="/action_page.php">
     <input type="text" id="order" size="50">
     <br>
    <input type="radio" name="coffee" value="1" onclick="myFunction()">Option 1<br>
    <input type="radio" name="coffee" value="2" onclick="myFunction()">Option 2<br>
    <input type="radio" name="coffee" value="3" onclick="myFunction()">Option 3<br>
    <input type="radio" name="coffee" value="4" onclick="myFunction()">Option 4<br>
</form>**




</body>
</html>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.