I am trying to build a quiz and I would like users to be able to submit answers to each question.
Here is the HTML:
<form id="question1">
Question 1:
<input type="hidden" class="question" value="1">
<input type="radio" class="answers" value="1" name="answer">Answer 1<br>
<input type="radio" class="answers" value="2" name="answer">Answer 2<br>
<input type="radio" class="answers" value="3" name="answer">Answer 3<br>
<input type="radio" class="answers" value="4" name="answer">Answer 4<br>
<input type="submit" class="submitquestion">
</form>
<form id="question2">
Question 2:
<input type="hidden" class="question" value="2">
<input type="checkbox" class="answers" value="5" name="answers1[]">Answer 1<br>
<input type="checkbox" class="answers" value="6" name="answers1[]">Answer 2<br>
<input type="checkbox" class="answers" value="7" name="answers1[]">Answer 3<br>
<input type="checkbox" class="answers" value="8" name="answers1[]">Answer 4<br>
<input type="submit" class="submitquestion">
</form>
<form id="question3">
Question 2:
<input type="hidden" class="question" value="2">
<input type="checkbox" class="answers" value="9" name="answers2[]">Answer 1<br>
<input type="checkbox" class="answers" value="10" name="answers2[]">Answer 2<br>
<input type="checkbox" class="answers" value="11" name="answers2[]">Answer 3<br>
<input type="checkbox" class="answers" value="12" name="answers2[]">Answer 4<br>
<input type="submit" class="submitquestion">
</form>
The number of questions and type of answers (checkbox/radio) will change.
I would like to be able to use submit each question without having to refresh the page and I would like to be able to submit answers each section at a time.
$(document).ready(function(){
$(".submitquestion").click(function(){
$(":checked").each(function() {
alert($(this).val());
});
});
});
The code above reloads the page.
The other problem is, if I select an answer for Question 1 (and I don’t submit it), then I move on to Question 2 and hit “submit” in Question 2, I will submit answers for Question 1 and Question 2. Is there a way to do this without having to specify ID’s (because there is not a set number of questions).
Any help is appreciated.
2
Answers
If you listen for a form to be submitted you will have direct access to the data within that form. Additionally, if you listen for a
form.submit()
and a submit button within that form is clicked it will trigger theform.submit()
(kind of a two birds with one stone thing).var form = $(this).closest('form');
– get only closest parent form.form.serialize()
– get serialized form dataAlso you can use
form.find('your_selector')
to find elements only in current formhttps://codepen.io/22dr22/pen/mdyNoYp