Reputation: 179
I'm trying to do something like this:
var size = skillsArray.length;
for (i = 0; i < size; i++) {
var divString = "'#Skill" + i +"'";
$(divString).append(skillsArray[i]);
}
To start out my prototype, skillsArray had 5 values. So my javascript was this:
$('#Skill0').append(skillsArray[0]);
$('#Skill1').append(skillsArray[1]);
$('#Skill2').append(skillsArray[2]);
$('#Skill3').append(skillsArray[3]);
$('#Skill4').append(skillsArray[4]);
My html was this:
<div id='Skill0'></div>
<div id='Skill1'></div>
<div id='Skill2'></div>
<div id='Skill3'></div>
<div id='Skill4'></div>
And everything worked fine.
Now that I want to work with larger dynamically sized arrays, I want to use loops.
So my first step was to write the html div tags out in a javascript loop, which worked:
for (i=0; i<size; i++)
{
html += "<div id='Skill" + i + "'></div>";
}
Before I tried step 2 which is what my question is about, it did show the first 5 skills just fine, and every skill after was just blank. (To be expected since I hadn't updated my javascript yet to do the append to each div, it still only did the first 5.)
So, I was ready to try step 2 and use a for loop for the appends. How can I do this? The code I pasted in at the very top did not fill each div with anything at all.
Thanks in advance for the help! -Holly
Upvotes: 0
Views: 197
Reputation: 3302
Try removing the single quotes in this line : var divString = "'#Skill" + i +"'";
like this:
var divString = "#Skill" + i;
Upvotes: 3
Reputation: 79032
Do everything in the same loop:
var size = skillsArray.length;
for (i = 0; i < size; i++) {
// create a div
var $elem = $("<div id='Skill" + i + "'></div>");
// append the skills to div
$elem.append(skillsArray[i]);
// append the div to body (or wherever)
$('body').append($elem);
}
Upvotes: 0
Reputation: 104775
You could try this
$("div[id^='Skill']").each(function(i) {
$(this).append(skillsArray[i]);
});
Upvotes: 0
Reputation: 71918
Get rid of the single quotes in your selector string:
var divString = "#Skill" + i;
Upvotes: 1