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

Time:03-16

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.

CodePudding user response:

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 >
            <button type="button" >ADD NUMBER BOX</button>
            <input type="number"  readonly>
        </div>
    `);
});

$('body').on('click', '.append-box-btn', function(){
    $(this).parent().append(
        `<div>
            <input type="number" ></input>
            <button type="button" >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 >ADD DIV</button>

CodePudding user response:

You can store the result of the sum in a cookie, with that you'll be able to get the result and to increment it as you wish!

Here are the function to get and set a cookie in JS:

function setCookie(cname, cvalue, exdays) {
  const d = new Date();
  d.setTime(d.getTime()   (exdays*24*60*60*1000));
  let expires = "expires="  d.toUTCString();
  document.cookie = cname   "="   cvalue   ";"   expires   ";path=/";
}


function getCookie(cname) {
  let name = cname   "=";
  let ca = document.cookie.split(';');
  for(let i = 0; i < ca.length; i  ) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

  • Related