Chris Chris - 1 year ago 106
jQuery Question

For loop JQuery outputs the same ID 4 times

I'm having some trouble with my

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

// 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



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


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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download