Home > OS >  How can I display array items using a loop?
How can I display array items using a loop?

Time:11-14

I'm trying to add an item into an empty array using .push inside loop then display it again but nothing is happening. Below is my current code:

$('.button').on('click', function(){
   const canvasArray = [];
   $('.box').each(function(){
       var boxName = $(this).text();
       canvasArray.push(boxName);
   });
   console.log(canvasArray);
});
<div class="catalog">
    <div class="box box-1">Red</div>
    <div class="box box-2">Blue</div>
    <div class="box box-3">Green</div>
    <div class="box box-4">Yellow</div>
</div>
<div id="result"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

In my console log, it returns something like this:

Array(4) [ "Red", "Blue", "Green", "Yellow" ]
0: "Red"
1: "Blue"
2: "Green"
3: "Yellow"
length: 4

I want to display the value of my canvasArray and append it to a DIV and I'm trying to do something like this:

$.each(canvasArray, function(index, value){
    $("#result").append(index   ": "   value   '<br>');
});

but nothing is happening and no error in my console log. Any idea?

CodePudding user response:

Your code works. Here it is. Perhaps you were unsure how to structure it all?

In this demo, the results div is populated upon a second button press - but you could alternately just move the $.each() code up into the first button's click handler (below the console.log, for example).

const canvasArray = [];
$('.button').on('click', function(){
   $('.box').each(function(){
       var boxName = $(this).text();
       canvasArray.push(boxName);
   });
   console.log(canvasArray);
});

$('.button2').on('click', function(){
  $.each(canvasArray, function(index, value){
    $("#result").append(index   ": "   value   '<br>');
  });
});
#result{
  position:fixed;
  top: 0px;
  left: 350px;
  width: 200px;
  height: 130px;
  margin-top:20px;
  background:wheat;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="catalog">
    <div class="box box-1">Red</div>
    <div class="box box-2">Blue</div>
    <div class="box box-3">Green</div>
    <div class="box box-4">Yellow</div>
</div>

<button class="button">Populate Canvas Array</button>
<button class="button2">Write Into Results Div</button>

<div id="result"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related