pixo-drone
pixo-drone

Reputation: 83

Trying to increment a variable by 1, but it's seemingly doubling itself

I've started making what will be a quiz. I want to move through the array after each question, however. Once I click the question_holder div (place holder for now, will be the correct answer eventually), variable x seems to be DOUBLING.

It goes 1, 2, 4, 8. However, when I alert out the value - it IS actually incrementing by one. It just doesn't present the right question though, it traverses through all of the questions until it reaches double it's value, and presents this question to the user.

Anybody know why this is happening?

function question(q, a, b, c) {
    this.q = q;
    this.a = a;
    this.b = b;
    this.c = c;
}

//all questions//
var q0 = new question("question1", "answer a", "answer b", "answer c")
var q1 = new question("question2", "answer d", "answer e", "answer f")
var q2 = new question("question3", "answer g", "answer h", "answer i")
var q3 = new question("question4", "answer j", "answer k", "answer l")
var q4 = new question("question5", "answer m", "answer n", "answer o")
var q5 = new question("question6", "answer p", "answer q", "answer r")
var q6 = new question("question7", "answer s", "answer t", "answer u")
var q7 = new question("question8", "answer v", "answer w", "answer x")

//array to hold all of the questions
var all_questions = [q0, q1, q2, q3, q4, q5, q6, q7];

/*i want to increment this variable by 1 each
    time time i run the new_Question() function.
    */
var x = 0;

$(document).ready(function () {

    new_Question();

    function new_Question() {
        $("#question_holder").text(all_questions[x].q);

        var answer_holders = $("answer_holder");

        $(".answer_holder").eq(0).text(all_questions[x].a);
        $(".answer_holder").eq(1).text(all_questions[x].b);
        $(".answer_holder").eq(2).text(all_questions[x].c);

        $("#question_holder").click(new_Question);

        x++;
        alert(x);
    }
})

Upvotes: 2

Views: 156

Answers (2)

Kaizen Programmer
Kaizen Programmer

Reputation: 3818

@Pointy is right.

One additional way to handle this though would be to unbind click before binding it again.

function new_Question() {
    $("#question_holder").text(all_questions[x].q);

    var answer_holders = $("answer_holder");

    $(".answer_holder").eq(0).text(all_questions[x].a);
    $(".answer_holder").eq(1).text(all_questions[x].b);
    $(".answer_holder").eq(2).text(all_questions[x].c);
    $("#question_holder").unbind("click").click(new_Question);

    x++;
    alert(x);
}

Upvotes: 1

Pointy
Pointy

Reputation: 413826

In your event handler ("new_Question") you're attaching it as an event handler on each click. You only need to do that once, so move that line to outside the function.

So, move this:

    $("#question_holder").click(new_Question);

to after the end of the "new_Question" function (but still inside the "ready" handler).

Upvotes: 4

Related Questions