How do multiply each value in the div with class="crtTotal" and have a div output that displays the answer: for example 1.75 x 3.65 x 2.10 = 13.41
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="box" class="boxlit">
<div class="box" data-id="75">Weston Bears - Cooks Hill United
<br>Home
<div class="crtTotal">1.75</div>
</div>
<div class="box" data-id="79">Logan Lightning - Brisbane City
<br>Draw
<div class="crtTotal">3.65</div>
</div>
<div class="box" data-id="81">Eastern Suburbs Brisbane - Moreton Bay United Jets
<br>Home
<div class="crtTotal">2.10</div>
</div>
<br>
<div class="total">Total</div>
Here Is the script I Came up with but works on sum (Addition), how do I Get It To Multiply for example 1.75 x 3.65 x 2.10 = 13.41
<script>
$(function() {
var sum = 0;
$('.crtTotal').each(function(){
sum += parseFloat(this.innerHTML, 10)
})
$('.total').text(sum);
})
</script>
Answer
The issue is because you initialise sum
to zero. Therefore every number you multiply by sum
is still zero. To fix this you could create an array of all values then use reduce()
to multiply them all together.
To display the output to 2DP you can use toFixed(2)
- but be aware this will convert the value to a string. Only call this function when presenting the value in the UI, not when it will be used for further calculation.
let values = $('.crtTotal').map((i, el) => parseFloat(el.textContent)).get();
let total = values.reduce((a, b) => a * b);
$('.total').text(total.toFixed(2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="box" class="boxlit">
<div class="box" data-id="75">Weston Bears - Cooks Hill United
<br>Home
<div class="crtTotal">1.75</div>
</div>
<div class="box" data-id="79">Logan Lightning - Brisbane City
<br>Draw
<div class="crtTotal">3.65</div>
</div>
<div class="box" data-id="81">Eastern Suburbs Brisbane - Moreton Bay United Jets
<br>Home
<div class="crtTotal">2.10</div>
</div>
<br>
<div class="total">Total</div>
</div>
Comments
Post a Comment