I am creating a multiple choice test hard coded in a form in HTML, and I'm using JavaScript and jQuery to perform all my actions related to the form. However, my onClick event doesn't seem to be firing off. Looking in the console I found that it hooks into the event with the id 'submission' and it moves to 'on' and at the click event it refreshes the browser instead of firing the submitAnswers() function.
<form name="javaScriptQuiz" id="jsTest">
<div class="form-group quiz-questions">
<h3>1. First question is either true or false.</h3>
<label for="q1a">
<input type="radio" name="q1" value="a" id="q1a"> A. True
</label>
<label for="q1b">
<input type="radio" name="q1" value="b" id="q1b"> B. False
</label>
<h3>2. Second question is either true or false.</h3>
<label for="q1a">
<input type="radio" name="q1" value="a" id="q1a"> A. True
</label>
<label for="q1b">
<input type="radio" name="q1" value="b" id="q1b"> B. False
</label>
<input class="btn btn-primary btn-lg" type="submit" name="submit" value="Submit!" id="submission">
</form>
$('#submission').on('click', function() {
console.log('Submit fires');
submitAnswers();
});
function submitAnswers() {
var total = 2;
var score = 0;
//captures each of the questions answers in a variable
var q1 = document.form['javaScriptQuiz']['q1'].value;
var q2 = document.form['javaScriptQuiz']['q2'].value;
//Validation
for(var i = 1; i <= total; i++ ){
if(eval('q' + i) == null || eval('q' + i) == ''){
alert('You missed a question');
return false;
}
}
// Are the answers to test
var answers = ['b', 'a'];
for(var i = 1; i <= total; i++){
if(eval('q' + 1) == answers[i - 1] ){
console.log('Evaluating answers');
score ++;
}
}
}
Try not to use name 'submit' for submit-type elements, this is not a good idea.
But the only error I see is missing s letter in function submitAnswers(): document.form instead of document.forms. I tried you code and it works in latest Firefox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With