So i am in the process of making a web app (experimental) that has a quiz in it. I am using a python file for questions and the function for the quiz. The problem is with the javascript, it is not selecting the tags that i want. Here's the code
{% extends "layout.html" %}
{% block title %}
Quiz Begin
{% endblock %}
{% block body %}
{% for q in qna %}
<div>
<h3>{{ q["question"] }} </h3>
<input class="{{ q['id'] }}" type="text">
<p class="{{ q['id'] }}" style="display:none;">{{ q["answer"] }}</p>
</div>
{% endfor %}
<footer>
<button id="check">Check Answer</button>
</footer>
<script>
// correct this or start from scratch because this is not working
var qna = {{ qna | tojson }};
var right = 0;
var wrong = 0;
document.querySelector("#check").addEventListener('click', function() {
var id, tmp, input, answer;
for (let q = parseInt("{{ qna[0]['id'] }}"); q <= parseInt("{{ qna|length }}"); q++) {
id = q.toString();
tmp = document.getElementsByClassName(id);
input = tmp.querySelector('input').value.toUpperCase();
answer = tmp.getElementByTagName('p').value.toUpperCase();
if (parseInt(input) == parseInt(answer)) {
right++;
}
else {
wrong++;
}
}
});
</script>
{% endblock %}
The python codes are
def quiz_begin():
return render_template("begin.html", qna=questions())
And
def questions():
return [{"id": 1,
"question": "2 + 2 = ?",
"answer": 4},
{"id": 2,
"question": "68 x 45 = ?",
"answer": 3060},]
The problem lies after the tmp variable is declared in the script. the tmp.querySelector doesn't seem to work and return the tag. It just stops there. I have tried some different functions like getElementByTagName but they dont seem to work either. if there is any other way then please help. Thanks for helping in advance.