sdhaus sdhaus - 1 month ago 8
jQuery Question

Jquery - each - return independent values

I have a grid of product of which I want to iterate through and create a new variable per div, called discount.

The problem I am experiencing is being able to independently access each of the divs, and run the operation to get the discount percentage. At the moment my output is every percentage discount listed under every product, rather then that specific div's discount value.

I think I need to alter the each function, though I am unsure as to the next step.

<div class="product">
<div class="text">
<span class="red">60</span>
<span class="grey">100</span>
</div>
</div>
<div class="product">
<div class="text">
<span class="red">40</span>
<span class="grey">100</span>
</div>
</div>

$('.product').each(function() {
var org = $(this).find(".text .grey").html().replace("$","").replace("WAS","");
var nwp = $(this).find('.text .red').html().replace("$","").replace("WAS","");
var OrigPrice = parseFloat(org);
var NewPrice = parseFloat(nwp);
var discount = ((((NewPrice/OrigPrice)-1)*-1)*100).toFixed(0);
$('<p>' + discount +' % off </p>').insertAfter('.grey');

});


Current output

<div class="product">
<div class="text">
<span class="red">60</span>
<span class="grey">100</span>
<p>"40 % off"</p>
<p>"60 % off"</p>
</div>
</div>
<div class="product">
<div class="text">
<span class="red">40</span>
<span class="grey">100</span>
<p>"40 % off"</p>
<p>"60 % off"</p>
</div>
</div>

Answer

You need to use $(this) in your insertAfter() call, so it only adds to the current DIV. Just like you do when you're getting the input values in org and nwp.

$('<p>' + discount +' % off </p>').insertAfter($(this).find('.text .grey'));
Comments