Reputation:
I am making a quiz website. Each quiz has a form which contains the questions (a div). Each question contains the options (a radio input, generated from a Flask for loop).
<div class="question">
{{squestions[question]}}
<br><br>
<div class="options">
{% for opt in opts[question] %}
<input type="radio" class="option" name="{{question}}" value="{{opt.answerId}}">
<a>{{opt.answer}}</a>
</input>
<br>
{% endfor %}
<br>
</div>
</div>
I am trying to show the user which answer is correct (after they select something). I thought this could be possible by iterating through each child of the question and coloring them appropriately (green if right, red if wrong) as such:
$("input[name=" + question + "]").children().each(function(i) {
if (correct == $(this).text) {
$(this).css('color', 'green');
} else {
$(this).css('color', 'red');
}
});
However, the children selector is returning [prevObject: r.fn.init(1)]
objects. My intention was for it to return the <a>
objects.
I don't think the problem is caused by the for loop because when the document is ready it has already generated all the elements.
Upvotes: 0
Views: 56
Reputation: 780974
<input>
elements can't have children. The answer text should be after the radio button, not a child of it.
<div class="question">
{{squestions[question]}}
<br><br>
<div class="options">
{% for opt in opts[question] %}
<input type="radio" class="option" name="{{question}}" value="{{opt.answerId}}">
<a>{{opt.answer}}</a>
<br>
{% endfor %}
<br>
</div>
</div>
Then your code can use .next()
to get the answer element. Also, .text
is a function, you need to call it with ()
.
$("input[name=" + question + "]").next('a').each(function(i) {
if (correct == $(this).text()) {
$(this).css('color', 'green');
} else {
$(this).css('color', 'red');
}
});
Upvotes: 1