Skip to content
Advertisement

How to find sum of multiple inputs (inputs can increase by add button) from different containers?

function appendDiv() {
  var e = "<div>
  <button onclick='appendBox(this)'>ADD NUMBER BOX</button>
  <input type='number' class='sumOfTotal' readonly>
  </div>"
  $("body").append(e);
}

function appendBox(This) {
  var e = "<div><input type='number' class='number'></input>
  <button onclick='removeNum(this)'>DELETE NUM</button></div>"
  $(This.closest('div')).append(e);
}

function removeNum(This) {
  $(This.closest('div')).remove();
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="js/lab2.js"></script>
  </head>
  <body>

    <button onclick="appendDiv()">ADD DIV</button>

  </body>
</html>

I want to update value of sumOfTotal every time I change input values. BUT each of someOfTotal boxes values have to be their div’s numbers’ sum.

Summary, each div has their own output (sumOfTotal) and inputs (number class). And each div’s own output has to be its own numbers’ sum.

Advertisement

Answer

First, I will recommend using event listeners instead of the inline javascript. Try this

function calculateSum($box){
    let numbers, sum;

    numbers = $box.find('.number'); // get all .number inputs
    numbers = numbers.filter((i, el) => !!el.value); // filter out empty fields
    numbers = numbers.map((i, el) => el.value).get(); // get entered values
    sum     = numbers.reduce((sum, val) => sum + parseFloat(val), 0); // sum numbers

    $box.find('.sumOfTotal').val(sum); // display sum
}

$('.append-div-btn').on('click', function(){
    $("body").append(`
        <div class="box">
            <button type="button" class="append-box-btn">ADD NUMBER BOX</button>
            <input type="number" class="sumOfTotal" readonly>
        </div>
    `);
});

$('body').on('click', '.append-box-btn', function(){
    $(this).parent().append(
        `<div>
            <input type="number" class="number"></input>
            <button type="button" class="remove-num-btn">DELETE NUM</button>
        </div>`
    )
}).on('click', '.remove-num-btn', function(){
    let $box = $(this).closest('.box');
    $(this).parent().remove();
    calculateSum($box);
}).on('input', '.number', function(){
    let $box = $(this).closest('.box');
    calculateSum($box);
});
.box {
    padding: 10px;
    border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button class="append-div-btn">ADD DIV</button>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement