0

I'm having some trouble with my for() loop in JQuery.

I have the following code:

for (i = 0; i < Object.keys(roster).length; i++) {
     fillMatchRoster(getUserEligible(roster[i].user_id), findUser(roster[i].user_id), findGamertag(roster[i].user_id));

     // Shows 4 different ID's
     alert(roster[i].user_id);

     // Outputs the same ID 4 times
     if(findGamertag(roster[i].user_id) != "") {
           $('.match_create_roster_playing').html("<input type='checkbox' value='" + roster[i].user_id + "'>");
     }
}

It should output 4 different ID's as checkbox values but instead I see 4 the same.

HTML output:

HTML output

UPDATE:

findGamertag():

function findGamertag(id) {
    var user = "";

    $.ajax({ 

        url: '/data/user_info.php',
        data: {user: id},
        dataType: 'json',
        async: false,
        type: 'post',
        success: function(json) {

            user = json.gamertag;

        },
        error: function(ts) {
            console.log("Error: " + ts.responseText);
        }
    });

    return user;
}
Chris
  • 1,574
  • 4
  • 16
  • 49

1 Answers1

2

I can bet that value 6 is the last user's id. That happens, cause you override the HTML of every td element with given class name. Line 9 literally replaces inner html on every iteration.

By adding .eq it seems like the result is correct.

Kamil Latosinski
  • 756
  • 5
  • 28
  • That seems to have done the trick! Could you explain what it does? – Chris Aug 30 '16 at 10:10
  • 1
    By calling `$('.match_create_roster_playing')` you get all elements with that class. Followed by `html()` **you replace every element's inner HTML** with new values every iteration. Adding `.eq` helps, cause on each iteration I take first row, and update it's html, then second row and so on. – Kamil Latosinski Aug 30 '16 at 10:13
  • Ahhh, I didn't know about that one! Thanks a lot! – Chris Aug 30 '16 at 10:13