I want to pick random product objects from an array and place the info that they contain in four different containers. All the containers is hard coded in html and has the same class name, and I want to iterate through them.
Below you see the code, and that I’m using .each for this task, which of course doesn’t work because every time the for loop runs it starts over again.
So, what is the best way to solve this?
function AddProducts(products) {
for(var i = 0; i < 4; i++) {
var number = Math.floor(Math.random() * products.length);
$('.product').each(function(index) {
$(this).find('h3').html(product[number].name);
});
}
}
<div class="row span12">
<ul class="thumbnails">
<li class="span3 product">
<div class="thumbnail padding">
<h3>Product name</h3>
<p>Description</p>
</div>
</li>
<li class="span3 product">
<div class="thumbnail padding">
<h3>Product name</h3>
<p>Description</p>
</div>
</li>
<li class="span3 product">
<div class="thumbnail padding">
<h3>Product name</h3>
<p>Description</p>
</div>
</li>
<li class="span3 product">
<div class="thumbnail padding">
<h3>Product name</h3>
<p>Description</p>
</div>
</li>
</ul>
</div>
If you want to pick random products and place them into each container without duplicates, you have to shuffle the array first:
DEMO
The
shuffle()function is taken from this question: How can I shuffle an array?Also, one of yourOkay, you’ve fixed that now 🙂<li>elements has the wrong class.producerinstead of.product.