JavaScript
x
17
17
1
function appendDiv() {
2
var e = "<div>
3
<button onclick='appendBox(this)'>ADD NUMBER BOX</button>
4
<input type='number' class='sumOfTotal' readonly>
5
</div>"
6
$("body").append(e);
7
}
8
9
function appendBox(This) {
10
var e = "<div><input type='number' class='number'></input>
11
<button onclick='removeNum(this)'>DELETE NUM</button></div>"
12
$(This.closest('div')).append(e);
13
}
14
15
function removeNum(This) {
16
$(This.closest('div')).remove();
17
}
JavaScript
1
13
13
1
<!DOCTYPE html>
2
<html lang="en" dir="ltr">
3
<head>
4
<meta charset="utf-8">
5
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
6
<script src="js/lab2.js"></script>
7
</head>
8
<body>
9
10
<button onclick="appendDiv()">ADD DIV</button>
11
12
</body>
13
</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
JavaScript
1
35
35
1
function calculateSum($box){
2
let numbers, sum;
3
4
numbers = $box.find('.number'); // get all .number inputs
5
numbers = numbers.filter((i, el) => !!el.value); // filter out empty fields
6
numbers = numbers.map((i, el) => el.value).get(); // get entered values
7
sum = numbers.reduce((sum, val) => sum + parseFloat(val), 0); // sum numbers
8
9
$box.find('.sumOfTotal').val(sum); // display sum
10
}
11
12
$('.append-div-btn').on('click', function(){
13
$("body").append(`
14
<div class="box">
15
<button type="button" class="append-box-btn">ADD NUMBER BOX</button>
16
<input type="number" class="sumOfTotal" readonly>
17
</div>
18
`);
19
});
20
21
$('body').on('click', '.append-box-btn', function(){
22
$(this).parent().append(
23
`<div>
24
<input type="number" class="number"></input>
25
<button type="button" class="remove-num-btn">DELETE NUM</button>
26
</div>`
27
)
28
}).on('click', '.remove-num-btn', function(){
29
let $box = $(this).closest('.box');
30
$(this).parent().remove();
31
calculateSum($box);
32
}).on('input', '.number', function(){
33
let $box = $(this).closest('.box');
34
calculateSum($box);
35
});
JavaScript
1
4
1
.box {
2
padding: 10px;
3
border: 1px solid #000;
4
}
JavaScript
1
2
1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
2
<button class="append-div-btn">ADD DIV</button>