How to select all elements of the same id in Javascript in Django

Question:

I have a table in Django where all the answers to a test are stored, but when I select them to compare with the answer provided by the user, all answers are equal to the first question. I know this has to do with getElementsById, which only selects the first element. But how do I select all elements with same id in HTML?

{% for resposta in questao.resposta_set.all %}

  <input type="hidden" id="resposta" name="resposta" value="{{resposta.resposta}}">
  <script type="text/javascript">
    function mostrarSel() {
      if (getRadioValor('opcao_escolhida') == document.getElementById("resposta").value) {
        alert('Resposta Correta');
      }
      else{
       alert('Resposta Incorreta');
      }
    }
    function getRadioValor(name){
      var rads = document.getElementsByName(name);
      for(var i = 0; i < rads.length; i++){
        if(rads[i].checked){
          return rads[i].value;
        }
      }

      return null;
    }

  </script>
{% endfor %}

Answer:

Your code isn't written correctly, you shouldn't script inside the loop, this js is affecting not only the loop's HTML, but everything that's rendered on the page.

The correct logic would be to separate HTML from JavaScript:

HTML

    {% for resposta in questao.resposta_set.all %}
        <div class="questao">
            <input type="hidden" name="resposta" value="{{resposta.resposta}}">
        </div>
    {% endfor %}

JavaScript (with jQuery)

var questoes = $('.questao');
$.each(questoes, function(num, questao){
    // sua lógica: 
    if (questao.find("name=[resposta]").val() == questao.find("name=[opcao]")){
        alert('opção correta');
    }
});

I don't know how your HTML code is, you just put a snippet. In this case I created a loop using jQuery that checks each question and fires an alert when it's correct. You can customize this, or even have an action trigger when the user selects an option and the code checks just that answer.

Scroll to Top
AllEscort