Ante Olić
Ante Olić

Reputation: 45

JS function looping double as expected

This is Javascript code for some quiz i am making. In my case table.length = 2, and function is repeating 2 times with parameter for first table and second.

But why command shows 4 times in console?

console.log("Hello");

.

function start(){
    var brojac =0;
    var table = document.getElementsByTagName("table");
    for (i =0; i<table.length ; i++){
        jednoPitanje(i);
        brojac += parseInt(jednoPitanje(i))

    }
    console.log("Sakupili ste ukupno " + brojac + " bodova");
}

function jednoPitanje(x) {
    var odgovori ="";
    var table = document.getElementsByTagName("table");
    var tableN = table[x];
    var input = tableN.getElementsByTagName("input")
    var brojInputa = tableN.getElementsByTagName("input").length;

    //Uzima bodove,kategoriju i index tocnih odgovora
    var bodovi =tableN.classList[2];
    var kategorija =tableN.classList[1];
    var tocni = tableN.classList[0];

    console.log("Hello");

    //Iteracija kroz sve checkboxsove u tablici
    for (j =0; j<brojInputa ; j++){
        if(input[j].checked==true){
            odgovori += tableN.getElementsByTagName("input")[j].value;
        }
    }
    if(odgovori == tocni){      
    }
    else{bodovi = 0;}

    return bodovi;
}

Upvotes: 0

Views: 47

Answers (1)

Mark
Mark

Reputation: 92440

You are calling console.log("Hello"); in the function jednoPitanje(). You call this function twice inside your loop:

 jednoPitanje(i);  // <-- this cause console.log() to run
 brojac += parseInt(jednoPitanje(i)) // <-- this also causes the console.log()

and since your loop runs twice it prints four times.

It's not immediately clear if you need that function to run twice, but if you don't, you can just remove the first call:

for (i =0; i<table.length ; i++){
    brojac += parseInt(jednoPitanje(i))
}

or if you prefer the extra clarity:

for (i =0; i<table.length ; i++){
    var bodovi = jednoPitanje(i);
    brojac += parseInt(bodovi)
}

Upvotes: 3

Related Questions