Matthew Barnes Matthew Barnes - 1 month ago 10
Javascript Question

Loop Only Showing Last Instance of Array

I'm trying to generate HTML content by looping through an array and inputting data into my HTML string.

I've tried using the following answer from Stack Overflow (with no luck):
JavaScript closure inside loops – simple practical example

Other answer's I have looked at are too complex for what I want to do.

Here is my original code:

var staticOptions = [
{
name : "option1",
id : "option1",
img : "img/extras/360-chasis.jpg"
},
{
name : "option2",
id : "option2",
img : "img/extras/lifing-eye.jpg"
},
{
name : "option3",
id : "option3",
img : "img/extras/360-window.jpg"
},
{
name : "option4",
id : "option4",
img : "img/extras/led-flood-light.jpg"
},
{
name : "option5",
id : "option5",
img : "img/extras/360-canteen-light.jpg"
}
];

for (var i = 0; i < staticOptions.length; i++ ) {
var optionHtml = '<div class="form-check width30">'
+ '<label class="form-check-label" for="'
+ staticOptions[i].id
+ '">'
+ '<input class="form-check-input" id="'
+ staticOptions[i].id
+ '" type="checkbox">'
+ staticOptions[i].name
+ '<!-- <span class="indiv-price">£300</span>-->'
+ '</label>'
+ ' </div>'
+ '<div class="info-img hide"><img src="'
+ staticOptions[i].img
+ '"></div>';

$("#bodyOptions").html(optionHtml);

};


This code as it stands only outputs the last item of my array. However, if I use the alert method to output the html it loops through all five objects in my array as expected.

Reading the top vote answer of the question above mentions "closures" I tried to adapt that answer to my code but it does not output anything (No errors showing either):

function createfunc(i) {
return function() {

var optionHtml = '<div class="form-check width30">'
+ '<label class="form-check-label" for="'
+ [i].id
+ '">'
+ '<input class="form-check-input" id="'
+ [i].id
+ '" type="checkbox">'
+ [i].name
+ '<!-- <span class="indiv-price">£300</span>-->'
+ '</label>'
+ ' </div>'
+ '<div class="info-img hide"><img src="'
+ [i].img
+ '"></div>';

$("#bodyOptions").html(optionHtml);

};
}

for (var i = 0; i < staticOptions.length; i++) {
staticOptions[i] = createfunc(i);
}


In summary all I want to do is create five pieces of HTML code which inputs the data for each instance from the array and write it in HTML to the page.

Thanks in advance.

Answer

Try:

$("#bodyOptions").html($("#bodyOptions").html() + optionHtml);

Seems like you are replacing whole #bodyOptions html with the new option, so what you need to do is add to what it contains already.

Comments