Having an issue with a for loop in jQuery only running once. Users is a array containing 4 items, and for each, it should append that item as a list element to userList, which is a ul. It appends the first element in the array as expected, but only that one. Not sure why it isn't running through the entire array?
$(document).ready(function() {
var $currentUser = $('<li class="user"></li>');
for(var i = 0; i < users.length; i++) {
$currentUser.text(users[i]);
$currentUser.appendTo('.userList');
}
//alert(users.length) returns "4".
});
Having an issue with a for loop in jQuery only running once. Users is a array containing 4 items, and for each, it should append that item as a list element to userList, which is a ul. It appends the first element in the array as expected, but only that one. Not sure why it isn't running through the entire array?
$(document).ready(function() {
var $currentUser = $('<li class="user"></li>');
for(var i = 0; i < users.length; i++) {
$currentUser.text(users[i]);
$currentUser.appendTo('.userList');
}
//alert(users.length) returns "4".
});
Share
Improve this question
edited Apr 8, 2015 at 1:25
Terry
14.2k9 gold badges57 silver badges84 bronze badges
asked Apr 8, 2015 at 1:12
user4313867user4313867
1
-
4
You don't create one
<li>
per user, you create one and overwrite its contents every iteration. – zerkms Commented Apr 8, 2015 at 1:17
5 Answers
Reset to default 5Try this
$(document).ready(function(){
for(var i = 0; i < users.length; i++) {
var $currentUser = $('<li class="user"></li>');
$currentUser.text(users[i]);
$currentUser.appendTo('.userList');
}
});
You're overwriting the element, instead of creating a new one for each user. Try the code above.
More jQuery'ish
$('.userList').append(function() {
return $.map(users, function(user) {
return $('<li />', {
'class' : 'user',
text : user
})
});
});
FIDDLE
You aren't adding a new <li>
for each iteration:
Here's a working solution:
for (var i = 0; i < users.length; i++) {
$('<li class="user"></li>'
.text(users[i])
.appendTo('.userList');
}
https://jsfiddle/2abqa5us/1/
You create the li
on the outside of the loop, then try to set the text of the same element to each user so you will overwrite it every iteration. Are you sure the last entry is not the one you see?
.text
will overwrite previous text which looks like you got one users only
try this.
$(document).ready(function(){
for(var i = 0; i < users.length; i++) {
var $currentUser = $('<li class="user"></li>');
$currentUser.text(users[i]);
$currentUser.appendTo('.userList');
}
});