Home > OS >  How do I multiply values within id and display answer?
How do I multiply values within id and display answer?

Time:07-06

How do multiply each value in the div with 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" >
        <div  data-id="75">Weston Bears - Cooks Hill United
            <br>Home
            <div >1.75</div>
        </div>
    

    <div  data-id="79">Logan Lightning - Brisbane City
        <br>Draw
        <div >3.65</div>
    </div>
    
    
    <div  data-id="81">Eastern Suburbs Brisbane - Moreton Bay United Jets
        <br>Home
        <div >2.10</div>
    </div>


    <br>

    <div >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>

CodePudding user response:

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" >
  <div  data-id="75">Weston Bears - Cooks Hill United
    <br>Home
    <div >1.75</div>
  </div>
  <div  data-id="79">Logan Lightning - Brisbane City
    <br>Draw
    <div >3.65</div>
  </div>
  <div  data-id="81">Eastern Suburbs Brisbane - Moreton Bay United Jets
    <br>Home
    <div >2.10</div>
  </div>
  <br>
  <div >Total</div>
</div>

  • Related