I have some product-elements with a base price and an extra price. The goal is to add the extra price to the base price and replace the base price with the newly calculated one.
Below is the code I have so far, the console.logs gives me all the right feedback, but the price won't append to the .subtotal div, no matter what I try.
jQuery(document).ready(function() {
var extra = jQuery('.extra');
extra.each(function() {
var $this = jQuery(this).html().replace(/[^\d,]/g, '');
var subtotal_dest = jQuery(this).siblings('.subtotal');
jQuery(subtotal_dest).css('border', '2px solid green');
var subtotal = jQuery(this).siblings('.subtotal').html().replace(/[^\d,]/g, '');
var newtotal = parseInt($this) + parseInt(subtotal);
var rendered_total = '€ ' + newtotal;
jQuery(rendered_total).appendTo(subtotal_dest);
console.log($this);
console.log(subtotal);
console.log(rendered_total);
console.log('-');
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>
</head>
<body>
<div class="product" style="margin-bottom:20px;">
<!--subtotal should be €10 -->
<div class="subtotal">€ 5,00</div>
<div class="extra">€ 5,00</div>
</div>
<div class="product" style="margin-bottom:20px;">
<!--subtotal should be €20-->
<div class="subtotal">€ 15,00</div>
<div class="extra">€ 5,00</div>
</div>
<div class="product" style="margin-bottom:20px;">
<!--subtotal should be €30-->
<div class="subtotal">€ 25,00</div>
<div class="extra">€ 5,00</div>
</div>
</body>
</html>
$('€ ' + newtotal')
does nothing useful.
Replace
jQuery(rendered_total)
with
jQuery("<div>").text(rendered_total).
Complete Runnable Code:
jQuery(document).ready(function() {
var extra = jQuery('.extra');
extra.each(function() {
var $this = jQuery(this).html().replace(/[^\d,]/g, '');
var subtotal_dest = jQuery(this).siblings('.subtotal');
jQuery(subtotal_dest).css('border', '2px solid green');
var subtotal = jQuery(this).siblings('.subtotal').html().replace(/[^\d,]/g, '');
var newtotal = parseInt($this) + parseInt(subtotal);
var rendered_total = '€ ' + newtotal;
jQuery("<div>").text(rendered_total).appendTo(subtotal_dest);
console.log($this);
console.log(subtotal);
console.log(rendered_total);
console.log('-');
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>
</head>
<body>
<div class="product" style="margin-bottom:20px;">
<!--subtotal should be €10 -->
<div class="subtotal">€ 5,00</div>
<div class="extra">€ 5,00</div>
</div>
<div class="product" style="margin-bottom:20px;">
<!--subtotal should be €20-->
<div class="subtotal">€ 15,00</div>
<div class="extra">€ 5,00</div>
</div>
<div class="product" style="margin-bottom:20px;">
<!--subtotal should be €30-->
<div class="subtotal">€ 25,00</div>
<div class="extra">€ 5,00</div>
</div>
</body>
</html>