Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - jQuery onClick event not firing

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 &nbsp;
  </label>
  <label for="q1b">
   <input type="radio" name="q1" value="b"  id="q1b"> B. False &nbsp;
  </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 &nbsp;
  </label>
  <label for="q1b">
   <input type="radio" name="q1" value="b"  id="q1b"> B. False &nbsp;
  </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 ++;
        }
    }
}
like image 277
Coffeeteer Avatar asked Nov 16 '25 20:11

Coffeeteer


1 Answers

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.

like image 187
kay27 Avatar answered Nov 19 '25 09:11

kay27



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!