Jacob Jacob - 5 months ago 16
Javascript Question

jQuery onclick call function

I've found a script that converts json file into quiz using jquery.

I am playing with it's code for almost a day now and I can't come with what I wanted to have.

Functions

quiz().init();
and
quiz().bindSubmit();
are called when page loaded.

What I want is the START button must be clicked first to load the Quiz.

$("#start").click(function(){
currentQuestion = 0;
questionCount = 0;
answerArray = [];
infoMode = false;
gotData = false;
inMemoryData = [];
quiz().init();
quiz().bindSubmit();
});


HTML:

<button type="button" id="start">Start</button>
<div id="quiz-content"></div>


It works at first click of START button also in the next clicks, it successfully reset the quiz and goes back to #1.

But the problem is after the first click of Start Button, the quiz won't work normally when submitting the quiz. The quiz began to stucked in #1.

For better understanding, JSfiddle here.

Edited:
Basically when the user click start button more than once,the quiz gets started from the beginning ,but didn't get to the next question(Gets stuck on the 1st question itself)

Answer

When you call bindSubmit function, inside it you are attaching to the submit event of the #quizForm. So when you press Start button twice, there two event handlers attached to the same event and that is because it is not behaving as it should be. So inside the bindSubmit function you need always disconnect all submit handlers ($(document).off('submit');), like this:

var bindSubmit = function () {
  $(document).off('submit');
  $(document).on('submit', '#quizForm', function (event) {
    event.preventDefault();
    next(this);
    quiz().init();
  });
};

Here is your original fiddle with mentioned update https://jsfiddle.net/t4p8x02b/35/