Tremors Tremors - 11 days ago 6
Javascript Question

How can I give Unique ID's while building HTML with JS?

So I'm trying to build store functionality and what I would like to do is be able to save the information of each object to storage by pressing the "add to cart" button on the page. I'm wondering how I could go about creating unique ID's for each "add to cart" button while using a for loop to create more than one item/feature box like below?

// temporary javascript thingy while we build the remove catalogs
var popularItems =
[
{
"itemImageSrc" : "./images/StoreProducts/StrawberryPi2ModelB.jpg",
"itemImageAlt" : "placeholder",
"itemDescription" : "<p> Strawberry Pi 3 Model B </p>",
"itemPrice" : "<p>$49.95</p>",
"itemPopular" : "true"
},
{
"itemImageSrc" : "./images/StoreProducts/StrawberryPiZero.jpg",
"itemImageAlt" : "placeholder",
"itemDescription" : "<p> Strawberry Pi Zero </p>",
"itemPrice" : "<p>$29.95</p>",
"itemPopular" : "true"
},
{
"itemImageSrc" : "./images/StoreProducts/StrawberryPiCase.jpg",
"itemImageAlt" : "placeholder",
"itemDescription" : "<p> Strawberry Pi Case </p>",
"itemPrice" : "<p>$10.95</p>",
"itemPopular" : "true"
},
{
"itemImageSrc" : "./images/StoreProducts/placeholder.png",
"itemImageAlt" : "placeholder",
"itemDescription" : "<p> Strawberry Pi Extension Kit </p>",
"itemPrice" : "<p>$149.95</p>",
"itemPopular" : "false"
}
];

document.write( '<div class="feature-container">' );

for ( var i = 0; i < popularItems.length; i++) {

if ( popularItems[i].itemPopular == "true" ) {

document.writeln('<div class="feature-box">');
document.write('<img src="');
document.writeln(popularItems[i].itemImageSrc);
document.write('" alt="');
document.write(popularItems[i].itemImageAlt);
document.writeln('">');

document.write('<div class="feature-box-model" id="var i">');
document.write(popularItems[i].itemDescription);
document.writeln('</div>');

document.write('<div class="feature-box-price">');
document.write(popularItems[i].itemPrice);
document.writeln('</div>');

document.writeln('<FORM>');
document.writeln('<INPUT TYPE="button" VALUE="Add To Cart" onclick="saveData()" id="unique">');
document.writeln('</FORM>');
document.writeln('</div>');

}


}

Answer

you can modify this line:

document.writeln('<INPUT TYPE="button" VALUE="Add To Cart" onclick="saveData()" id="unique">');

to be:

document.writeln('<INPUT TYPE="button" VALUE="Add To Cart" onclick="saveData()" id="item_'+i+'">');