Как изменить цвет конкретной опции радиокнопки, используя javascript? - PullRequest
0 голосов
/ 08 мая 2020

Я создаю приложение для викторины, используя JavaScript. Я хочу изменить цвет кнопки ввода, когда пользователь нажимает на нее в соответствии с ответом. если ответ верный, необходимо изменить цвет на красный, а если ответ неверен, цвет необходимо изменить на красный. Для каждого вопроса нужно выбирать только один вариант. Если пользователь выбрал один вариант, он должен выделить зеленый цвет, иначе красный. если красный, то нужно выделить зеленый. Не должен давать другой возможности пользователю каждый раз нажимать на параметры, чтобы увидеть, какой вариант правильный.

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 **

    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";         

          }
    }

Я только что написал document.getElementsByName ('option' ) .style.color = "красный"; ** но не работает, отображается ошибка "** Uncaught TypeError: Невозможно установить свойство" цвет "неопределенного

1. Что не так с этой строкой. Не могли бы вы помочь мне, ребята. enter image description here

Это объект json. enter image description here

Ответы [ 2 ]

1 голос
/ 08 мая 2020

Добавьте функцию проверки к каждому событию onchange радиоэлемента, а затем передайте этот радиоэлемент в качестве аргумента:

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

Затем измените функцию javascript соответствующим образом:

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"
  }
}

Вот созданный мной пример, демонстрирующий, что вы пытаетесь сделать:

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 голос
/ 08 мая 2020

Проблема связана с document.getElementsByName('option').style.color, поскольку вы пытаетесь получить элемент по имени тега, который возвращает массив всех совпадающих элементов, а в html нет элемента с именем option. Предполагая, что вы хотите показать, правильный или неправильный выбранный ответ. Если верно, покажите зеленый цвет для текста или красный в случае неправильного ответа.

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";         
  }
}

Другой простой способ - прикрепить элемент id к label и передать этот идентификатор в 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:

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

Обновить, отключить остальные переключатели Обернуть все ярлыки в 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;
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...