I’m working on an HTML5 quiz, where I’m using radio buttons for yes or no questions, and then assigning each radio button a value of 0 or 1, then store the numerical value as a variable, then add all the variables together to score the quiz.
UPDATE!!!
Hey! I made the changes you suggested, but when I call the variable, it still comes up as undefined:
Here is my html:
<form class="answer" id="question_one">
<input type="radio" class="styled" name="first_answer" value="1"/><!-- POSITIVE ANSWER -->
<div class="answer_text">Yes</div>
<input type="radio" class="styled" name="first_answer" value="0" /><!-- NEGATIVE ANSWER -->
<div class="answer_text">No</div>
</form>
Here is my JavaScript:
$('#question_one input:radio[name=first_answer]').on('change', function () {
var first_question = parseInt(
$("input[name=first_answer]:checked").val()
);
});
I tried to include a bit more specificity to the jQuery object by only targeting Radio Buttons with name=first_asnwer. Maybe I screwed up?
I think your issue here is the understanding of the
$(document).ready()function. This function is executed once all the dependencies of the page have been loaded – CSS, JavaScript, etc…You have set your variables as soon as this function is executed which is probably before you even click on your first radio button! The solution here would be to only calculate the values after the user has finished answering. Possibly on a change event of the radio element –
Here is a simple demo