Antonio D'Angelo
Antonio D'Angelo

Reputation: 119

only the last value of the array is returned when constructed in a for loop

I'm having a problem with this function:

var url = "";

function multiSearchTest() {
    var formData = $("#frmSearch").serialize();
    var look = new Array("SDO", "AR", "AS", "AC", "AP", "GEMO", "CC");
    var count;

    for(count = 0; count < look.length; count++){
       url = "index.php?Page&module=mod_page&action=dispatch&todo=cerca"+look[count]+"&" + formData;
       console.log(url);
    var test = "#"+look[count]+"result";

    $.get(url, function(data) {
           $(test).html(data);
           console.log("TEST VAL => " + test);
        });
    }
}

As you can see the url construction is perfect...but when I say where to print the output it return me only the last val of the array. Any ideas or suggestion? Where is my mistake?

Upvotes: 0

Views: 99

Answers (1)

Sudharsan S
Sudharsan S

Reputation: 15393

Declare var test outside of forloop. and make it as array.beacuse the var test in for loop every time it creates a new object so declare the variable test in outside of for loop

 function multiSearchTest() {
        var formData = $("#frmSearch").serialize();
        var look = new Array("SDO", "AR", "AS", "AC", "AP", "GEMO", "CC");
        var count;
    var test = [];

        for(count = 0; count < look.length; count++){
           url = "index.php?Page&module=mod_page&action=dispatch&todo=cerca"+look[count]+"&" + formData;
           console.log(url);
           test[count] = "#"+look[count]+"result";

        $.get(url, function(data) {
               $(test[count]).html(data);
               console.log("TEST VAL => " + test[count]);
            });
        }
    }

Upvotes: 2

Related Questions