如何将值从Django模板传递到javascript函数?

时间:2019-03-29 07:02:17

标签: javascript django django-templates

我正在尝试从Django模板中选中的单选按钮发送值,并在提交表单时收到警报消息。如何使用javascript函数来向用户发出警报?

这是Django模板

<form name="taketest">
        <ul>
        {% for q, opts in quesBank.items %}
                {{ forloop.counter }}{{q}}
                <ol>
                        <label class='radiocontainer'><input type="radio" name="q{{forloop.counter}}" value="{{opts.0}}">{{opts.0}}</input></label><span class='checkmark'>
                        <label class='radiocontainer'><input type="radio" name="q{{forloop.counter}}" value="{{opts.1}}">{{opts.1}}</input></label><span class='checkmark'>
                        <label class='radiocontainer'><input type="radio" name="q{{forloop.counter}}"value="{{opts.2}}">{{opts.2}}</input></label><span class='checkmark'>
                        <label class='radiocontainer'><input type="radio" name="q{{forloop.counter}}" value="{{opts.3}}">{{opts.3}}</input></label><span class='checkmark'>

                </ol>
        {% endfor %}
        </ul>
        <div class="text-right">
          <button class="btn btn-outline-info" type="submit" onsubmit="return submitAnswers(JSON.parse('answers=[{% for a in correctAnswer %}'{{a|safe}}',{% endfor %}])')">Submit</button>
        </div>
</form>

这是javascript文件

function submitAnswers(answers){
  var total = answers.length;
  var score = 0;
  var choice = []

//new dynamic method 1
  for(var i = 1; i <= total; i++){

    choice[i] = document.forms["taketest"]["q"+i].value;
  }
  // new dynamic method 1 for checking answer
  for(i = 1; i <= total; i++){
    if(choice[i] == answers[i]){
      score++;
    }
  }

  //Display Result

  window.alert("You scored " + score + " out of " + total);

  return false;
}

这有什么问题吗?

0 个答案:

没有答案