andryuu87
andryuu87

Reputation: 37

Using variable outside of jquery.click function?

I want to call a local variable, totalYes, outside of the jquery .click function. To do this I should make it a global variable, right? Originally, the code looked like:

var answers = [thing1, thing2, thing3, thing4, thing5, thing6, thing7, thing8, thing9, thing10, thing11, thing12];

var answers2 = [answers2array12items];

$("#submmit").click(function() {
    var totalYes=0;
    function checkAnswers() {
        for(var i=0; i<answers.length; i++) {
            var userAnswer = document.getElementById("b"+i).value.toLowerCase();
            if (answers.indexOf(userAnswer.toLowerCase()) !== -1 || answers2.indexOf(userAnswer.toLowerCase()) !== -1) {
                totalYes++;
                $("#correcto").show();
            } else {
                $("#incorrecto").show();
            }
        }
    }
    checkAnswers();
    alert(totalYes);
});

And it works fine, however, I want to use it in:

$("total").click(function(){
    alert(totalYes);
});

So I took totalYes, and make it "global", outside the function. The new version is:

var answers = [thing1, thing2, thing3, thing4, thing5, thing6, thing7, thing8, thing9, thing10, thing11, thing12];

var answers2 = [answers2array12items];

var totalYes = 0;

$("#submmit").click(function() {
    function checkAnswers() {
        for(var i=0; i<answers.length; i++) {
            var userAnswer = document.getElementById("b"+i).value.toLowerCase();
            if (answers.indexOf(userAnswer.toLowerCase()) !== -1 || answers2.indexOf(userAnswer.toLowerCase()) !== -1) {
                totalYes++;
                $("#correcto").show();
            } else {
                $("#incorrecto").show();
            }
        }
    }
    checkAnswers();
    alert(totalYes);
});

But in the new code, instead of adding 1 to totalYes for every correct answer, and increasing totalYes like this: "1,2,3,4,5,6,7,8,9,10,11,12", it increases as: "1,3,6,10,15,21,27,33,39,46,54". I have tried changing the totalYes modifier inside of checkAnswers(), from totalYes++; to totalYes+=1;, but the problem persists.

Also, I would like to know, why the alert box shows up twice every time, instead of just once?

edit: here's the html and css for #total and #submmit:

<div class="nextsa1" id="total"><strong>TOTAL</strong></div>

<input type="button" id="submmit" value="GO">

Upvotes: 1

Views: 610

Answers (1)

collapsar
collapsar

Reputation: 17238

Your code Appears to search the complete answer List each Time it is called upon the user entering a new answer. Therefore, on each invocation the Test Inside your Click handler is successful for the current and all previous answers, which explains the Delta pattern of the totalYes variable.

Remedy: init totalYes to 0 as the first Instruction inside the Click Handler.

Upvotes: 1

Related Questions