Skip to content

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>

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

function removeNum(This) {
<!DOCTYPE html>
<html lang="en" dir="ltr">
    <meta charset="utf-8">
    <script src=""></script>
    <script src="js/lab2.js"></script>

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


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.


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 =, 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(){
        <div class="box">
            <button type="button" class="append-box-btn">ADD NUMBER BOX</button>
            <input type="number" class="sumOfTotal" readonly>

$('body').on('click', '.append-box-btn', function(){
            <input type="number" class="number"></input>
            <button type="button" class="remove-num-btn">DELETE NUM</button>
}).on('click', '.remove-num-btn', function(){
    let $box = $(this).closest('.box');
}).on('input', '.number', function(){
    let $box = $(this).closest('.box');
.box {
    padding: 10px;
    border: 1px solid #000;
<script src=""></script>
<button class="append-div-btn">ADD DIV</button>