Chris Chris - 3 months ago 11
jQuery Question

For loop JQuery outputs the same ID 4 times

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;
}

Answer

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.