hiddenuser hiddenuser - 5 months ago 12
Javascript Question

JS Loop inside the loop

Hello I have little problem with jquery.
First, what I have:


VW BORA 1.9TDI 1990 1995

Audi A3 2.0TFSI 2006 2008


What I want achive:


VW BORA 1.9TDI 1990

VW BORA 1.9TDI 1991

VW BORA 1.9TDI 1992

VW BORA 1.9TDI 1993

VW BORA 1.9TDI 1994

VW BORA 1.9TDI 1995

Audi A3 2.0TFSI 2006

Audi A3 2.0TFSI 2007

Audi A3 2.0TFSI 2008



My code:

<div class="make">
<div class="name">VW BORA 1.9TDI</div><div class="start">1990</div><div class="end">1995</div>
</div>
<div class="make">
<div class="name">Audi A3 2.0TFSI</div><div class="start">2006</div><div class="end">2008</div>
</div>


and my JS code:

$('div[class="make"]').each(function(index){
var html = '';
var start = $('.start').text();
var end = $('.end').text();
var name = $('.name').text();

for (i=start; i<=end; i++) {
html += '<div class="'+i+'">'+name+' '+i+'</div>';
}
$("#content").html(html)
});


If there is class .make with one content it's fine, but if class .make appears many times with different content, all the content is put together but it should be separate.

Like this:


VW BORA 1.9TDIAudi A3 2.0TFSI 19902006

VW BORA 1.9TDIAudi A3 2.0TFSI 19902007

VW BORA 1.9TDIAudi A3 2.0TFSI 19902008

VW BORA 1.9TDIAudi A3 2.0TFSI 19902009


Answer

This would work for you : note that $(".class") return always an array , so in your case you should access one by one and this by using the index value.

$('div[class="make"]').each(function(index){
  
   var html = '';
   var links = '';
   var start = parseInt($($('.start')[index]).text());
   var end = parseInt($($('.end')[index]).text());
   var name = $($('.name')[index]).text();
   
   for (i=start; i<=end; i++) {
       html += '<div class="'+i+'">'+name+' '+i+'</div>';
   }
   $("#content").append(html)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="make">
   <div class="name">VW BORA 1.9TDI</div><div class="start">1990</div><div class="end">1995</div>
</div>
<div class="make">
   <div class="name">Audi A3 2.0TFSI</div><div class="start">2006</div><div class="end">2008</div>
</div>
<br><br>
<div id="content"></div>

Comments