birgit
birgit

Reputation: 1129

Fill divs with strings from array

I want to have divs fill with text stored in a jquery array randomly. My html looks like

<div class="row">
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
</div>

In my jQuery I have an array that looks like

var fruits = ["Apple", "Pear", "Orange"]

Each cell should be filled with a fruit randomly but I am stuck with iterating over the correctly and picking random values for each div with the class cell. This code obviously does not work:

$.each(fruits), function(fruit) {
    var fruit = fruits[Math.floor(Math.random()*fruits.length)];
    $('.row .cell').text(fruit);
}

How can I make the random guess happen exactly 5 times and fill the divs correctly?

Upvotes: 1

Views: 1449

Answers (4)

M Chang
M Chang

Reputation: 78

$('.row .cell').text(fruit) will change text for every ".cell" Here's a quick correction:

var fruits = ["Apple", "Pear", "Orange"]; 

$.each(fruits, function(i, fruit) {
 var fruit = fruits[Math.floor(Math.random()*fruits.length)];
 $('.cell').eq(i).text(fruit);
});

Upvotes: 0

Harshit Gupta
Harshit Gupta

Reputation: 739

Try this solution

function getRandomInt(min, max) {
  return Math.random() * (max - min) + min;
}

This function will generate the values between the min and max length of array so that you will get appropriate value.

$('.cell').each(function(){
   $(this).text(fruits[getRandomInt(0, fruits.length)]);
});

Upvotes: 0

Tahir Ahmed
Tahir Ahmed

Reputation: 5737

This should do it:

var fruits = ['Apple', 'Pear', 'Orange'];
$('.cell').each(function(index) {
  $(this).text(fruits[Math.floor(Math.random()*fruits.length)]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="row">
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
</div>

You needed to iterate on .cell elements instead of fruits array. Hope this helps.

Upvotes: 3

DGS
DGS

Reputation: 6025

Try this instead

$('.cell').each(function(){
   $(this).text(fruits[Math.floor(Math.random()*fruits.length)])
})

Upvotes: 5

Related Questions