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

0

I have a table in Django where all the answers to a test are stored, but when I select them to compare with the response provided by the user, all the answers are the same as the first question. I know this has to do with getElementsById, which only selects the first element. But how do I select all elements of the 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 %}
    
asked by anonymous 07.11.2017 / 14:41

1 answer

0

Your code is not spelled correctly, you should not create a script within the loop, this js is affecting not only the HTML of the loop, but everything rendered on the page.

The correct logic would be to separate the 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 do not know how your HTML code is, you just put in a snippet. In that case I created a loop using jQuery that checks each question and fires a alert when correct. You can customize this, or even trigger an action when the user selects an option and the code checks only that response.

    
08.11.2017 / 15:38