Calculate sum on-click and append total?

Viewed 1351

I want to calculate numbers in some DIV boxes and append the total in another DIV.

How can I make this work on-click of the box class as another function adds the values to the box dynamically?

I have tried various messy ways like wrapping the whole code in window.onclick. https://jsfiddle.net/esw6dbLn/1/

var total =0;
$('.box > .box_content > .box_price').each(function(){
  total += parseInt($(this).text());
});
$('.container').append("<div class='sum'>Total : "+total+"</div>");
console.log(total);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<div class="container">
<div class="box">
    <div class="box_content">
        <div class="box_price">100</div>
    </div>
</div>
<div class="box">
    <div class="box_content">
        <div class="box_price">200</div>
    </div>
</div>
</div>

4 Answers

You can use click event on box_price div then get value of div which is been clicked and also the sum div value add them and display them inside your sum div.

Demo Code :

var total = 0;
$('.box > .box_content > .box_price').each(function() {
  total += parseInt($(this).text());
});
$('.container').append("<div class='sum'>Total :<span> " + total + "</span></div>");
console.log(total);

$(".box_price").click(function() {
  //get price which is clicked then add with sum
  var price = parseInt($(this).text()) + parseInt($(".sum span").text().trim())
  $(".sum span").text(price) //display in span
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="box">
    <div class="box_content">
      <div class="box_price">100</div>
    </div>
  </div>
  <div class="box">
    <div class="box_content">
      <div class="box_price">200</div>
    </div>
  </div>
</div>

You can listen for the .container click so anything inside the container will trigger the event and then do the calculation.

DEMO: https://jsbin.com/bokoman/edit?html,js,console,output

// Get the container
const container = document.querySelector('.container');

// Create an empty <span> and added to the end of the container
const totalEl = document.createElement('span');
container.appendChild(totalEl);

// listen for all the click but only do somethig if one of it childs was clicked
container.addEventListener('click', function(e) {
  if (!e.target.classList.contains('container')) {
    const prices = document.querySelectorAll('.box_price');
    let total = 0;
    prices.forEach(item => {
      total += parseInt(item.innerText, 10)
    })

    // Add the total to the total element we created
    totalEl.innerHTML = total
  }
})

You can put an empty div in your HTML and update it via an event listener that is added to each .box element, like:

// Finds all the boxes and calls `sumBoxes` whenever one is clicked
const boxes = document.getElementsByClassName("box");
for (let box of boxes){ box.addEventListener("click", sumBoxes); }

// Defines listener
function sumBoxes(event) {
  var total = 0;
  $('.box > .box_content > .box_price').each(function() {
    total += parseInt($(this).text());
  });
  $('.sum').html("Total : " + total); // Replaces contents of `.sum`
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<div class="container">
  <div class="box">
    <div class="box_content">
      <div class="box_price">100</div>
    </div>
  </div>
  <div class="box">
    <div class="box_content">
      <div class="box_price">200</div>
    </div>
  </div>
  <!-- Empty div to recieve sums -->
  <div class="sum"></div>
</div>

var total =0;
calculateResult = () =>{
    total = 0;
  $('.box > .box_content > .box_price').each(function(){
    console.log()
    total += parseInt($(this).text());
  });
  $('#sum').html("total:" + total);
}


$( "#target" ).click(function() {
$('.container').append("<div class='box'><div class='box_content'><div class='box_price'>100</div></div></div>");
calculateResult();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
</div>
<div id="result">
  <div class='sum' id="sum">0</div>
</div>
<div id="target">
  Add
</div>

Related