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">
html? i.e.g,htmlfor$("submmit"),$("total")? Thanks