简体   繁体   English

如何使用 javascript 更改特定单选按钮选项的颜色?

[英]How to Change the color of the particular radio button option using javascript?

I am creating the quiz app using JavaScript.我正在使用 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.每个问题只需要 select 一个选项。 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: 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 ** **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";我刚刚写了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. 1.那条线有什么问题。 can u please help me guys.你能帮帮我吗? 在此处输入图像描述

This is the json object.这是 json object。 在此处输入图像描述

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.问题在于document.getElementsByName('option').style.color ,因为您尝试按标签名称获取元素,它返回所有匹配元素的数组,并且 html 中没有名为option的元素。 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另一种简单的方法是将id元素附加到label并将该 id 传递给check方法

<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: 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 .更新,禁用单选按钮的 rest将所有标签包装在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;
  }
}

Add the check function to each radio element's onchange event and then pass that radio element as the argument:将检查 function 添加到每个无线电元素的 onchange 事件,然后将该无线电元素作为参数传递:

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

Then change the javascript function accordingly:然后相应地更改 javascript function:

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();" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM