shyama
shyama

Reputation: 331

Loop in jquery based on razor loop

I have a for each loop in my razor view (MVC4)

 @foreach (var fe in ViewBag.FeatureProducts)
  {

    <div class="product-details" style="display:none;">@Html.Raw(fe.Details)</div>
    <div class="product-qty-dt">   </div>

  }      

in the each loop i have to extract the @html row content and display in to the div 'product-qty-dt'.

For that I write the following jquery,

$(document).ready(function () {        
       var data = $('.product-details p').map(function () {
           return $(this).text();
       }).get();           
       //product availability
       var availability = data[2].split(",");        
       $.each(availability, function (i) {
           $('.product-qty-dt').append( availability[i])
       });

   });

But this was only consider the last foreach raw. how can i call this jquery in each loop call.

For example, In first loop,

  <div class="product-details" style="display:none;"><p>Lorem, Ispum</p><p>doler emit,fghjh</p><p>9gm</p></div>
  <div class="product-qty-dt"> 9gm  </div>

second loop

 <div class="product-details" style="display:none;"><p>Lorem, Ispum</p><p>doler emit,fghjh</p><p>5gm</p></div>
 <div class="product-qty-dt"> 5gm  </div>

Thirdloop

 <div class="product-details" style="display:none;"><p>Lorem, Ispum</p><p>doler emit,fghjh</p><p>3gm</p></div>
 <div class="product-qty-dt"> 3gm  </div>

Upvotes: 0

Views: 769

Answers (2)

Chris du Preez
Chris du Preez

Reputation: 539

This should do the trick. Also the data array is still used just incase you would like to access other data portions stored in product-details.

$(".product-details").each(function()
    {
        var data = $(this).find('p').map(function () { return $(this).text() }).get();
        $(this).next('.product-qty-dt').text(data[2]);
    })

Upvotes: 1

user3559349
user3559349

Reputation:

The following will add the text of the last <p> in a <div class="product-details"> element into the corresponding <div class="product-qty-dt"> element

$('.product-details').each(function () {
  var t = $(this).children('p').last().text();
  $(this).next('.product-qty-dt').text(t);
}) 

Upvotes: 1

Related Questions