1

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?

4 Answers 4

5

Try this instead

$('.cell').each(function(){
   $(this).text(fruits[Math.floor(Math.random()*fruits.length)])
})
Sign up to request clarification or add additional context in comments.

1 Comment

You can also use index of each()
3

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.

1 Comment

ha! @DGS beat me to it :)
0

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)]);
});

Comments

0

$('.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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.