Issue
I'm trying to create a quiz, where the question is shown on the left and the user fills in the question on the right, and then there's a button next to these that you click to see if your input was correct.
My problem is that the code only seems to target the first button of the first question, regardless of which button I press. So if my quiz has 10 questions (they are generated by the user in a previous step), if I click on the result button for question number 7 it still only evaluates the first question.
I'm not sure how to give a unique ID to each question that is generated, so I'm hoping you can help me find a way to make Jquery target the right question. Here is the relevant code:
HTML:
{% for element in range(length) %}
<div class="m-5" id="quizSection">
<ul class="list-group list-group-horizontal" id="">
<li class="list-group-item flex-fill" id="quizQuestion">{{ quiz_questions[element] }}</li>
<li class="list-group-item flex-fill">
<div class="form-group">
<label for="quizInput">Check</label><br>
<input type="text" id="quizInput"><br>
</div>
<button class="btn btn-primary m-2 quizButton">See if correct</button>
</li>
<li id="result">
<p>
if true: {{ result }}
</p>
</li>
</ul>
</div>
{% if quiz_questions[element] == quiz_answers[element] %}
<p>{{ quiz_questions[element] }}</p>
<p>{{ quiz_answers[element] }}</p>
{% endif %}
{% endfor %}
Jquery:
$(document).ready(function() {
$('.quizButton').click(function() {
var answer = $('#quizInput').val();
var question = $('#quizQuestion').text();
req = $.ajax({
url: '/evaluate',
type: 'GET',
contentType: 'application/json',
data: {answer: answer, question: question}
});
req.done(function(data) {
$('#result').text(data.result);
});
$('#quizSection').fadeOut(500).fadeIn(500);
});
});
Solution
Convert different id
to class
first as you cannot have the same value for multiple id
attributes on an HTML page. It creates an Invalid HTML.
Convert these:
id="quizInput"
to class="quizInput"
id="quizQuestion"
to class="list-group-item flex-fill quizQuestion"
id="result"
to class="result"
After that, You need to address the corresponding question and answer of the pressed button and you can do it via .closest
var obj = $(this);
var answer = obj.closest('ul').find('.quizInput').val();
var question = obj.closest('ul').find('.quizQuestion').text();
req.done(function(data) {
obj.closest('ul').find('.result').text(data.result);
});
Note: Since id
is treated as a unique identifier by jQuery, whenever you use it it will give you first occurrence data no matter how many times it's repeated. That's why the class
concept is used. (to address multiple elements that possess the same behavior)
Answered By - Death-is-the-real-truth
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.