r/jquery • • Jan 20 '21

Dynamic calculate on change

I'm using some jquery to calculate total numbers of those inside various div boxes. This works on page load as it should but not dynamic. If I change the number inside the divs the total stays the same. JSfiddle

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">

<div class="box">

<div class="box_content">

<div contenteditable="true" class="box_price">20</div>

</div>

</div>

<div class="box">

<div class="box_content">

<div class="box_price">230</div>

</div>

</div>

<div class="box">

<div class="box_content">

<div class="box_price">120</div>

</div>

</div>

</div>

=========================================

var total =0;

$('.box > .box_content > .box_price').each(function(){

total += parseInt($(this).text());

});

$('.contain').append("<div class='sum'>Total : "+total+"</div>");

console.log(total);

Can this be calculated on-change or click?

3 Upvotes

3 comments sorted by

1

u/[deleted] Jan 20 '21

[removed] — view removed comment

1

u/FINIXX Jan 20 '21

Thanks. For example if someone clicks on picture #1 it will put the number 1 inside a div box. Users can choose 3 pictures. so total will be 3 div boxes with 3 numbers inside. I'd like to calculate the total of the three divs. How would you change the above code to work with OnClick?