user1640900 user1640900 - 19 days ago 8
jQuery Question

Two nested for each loops with objects and div selectors

I am struggling with two each loops. What I want to achieve is match corresponding object to correct each iteration.

There's my fiddle. In each div there's the same output, it should be 1,2,3 instead of 3,3,3.



jQuery('.get-total-numbers').each(function(i, e) {
var $el = jQuery(e);

var json = '["1","2","3"]';
var arr = $.parseJSON(json);

myjson = json;
json2 = JSON.parse(json);
jQuery.each(json2, function(index, e) {
console.log(e);
$el.text(e);


});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="get-total-numbers">

</div>

<div class="get-total-numbers">

</div>

<div class="get-total-numbers">

</div>




Answer

Try this:

jQuery('.get-total-numbers').each(function(i, e) {
  var $el = jQuery(e);

  var json = '["1","2","3"]';
  var arr = $.parseJSON(json);

  myjson = json;
  json2 = JSON.parse(json);
  $el.text(json2[i]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="get-total-numbers">

</div>

<div class="get-total-numbers">

</div>

<div class="get-total-numbers">

</div>