I only need a function so that I can divide #total by the total of names that were entered on the button. If you know the answer please help me, I’m a newbie in Javascript.
JavaScript
x
20
20
1
function ir() {
2
3
const nombre = document.getElementById("nombre").value;
4
5
let monto = document.getElementById("monto").value;
6
7
const total = document.getElementById("total");
8
const final = document.getElementById("final");
9
const aporte = document.getElementById("aporte");
10
11
const lineBreak = document.createElement("br");
12
let newTotal = document.createTextNode(` ${nombre} : ${monto} `);
13
total.appendChild(lineBreak);
14
total.appendChild(newTotal);
15
16
monto = Number(monto) + Number(final.innerHTML);
17
18
final.innerHTML = `${monto}`;
19
aporte.innerHTML = `${monto}`;
20
};
JavaScript
1
14
14
1
<h1>Expenses app</h1>
2
<p>Enter how much each person spent</p>
3
<p>Nombre</p>
4
<input type="text" id="nombre">
5
<br>
6
<p>Monto</p>
7
<input type="number" id="monto">
8
<br>
9
<button onclick="ir()">Enviar</button>
10
<br>
11
<p>Total: <span id="final"></span> </p>
12
<div id="total">
13
</div>
14
<p>A cada uno le toca aportar: <span id="aporte"></span></p>
Advertisement
Answer
i hope this fast written solution helps you.
JavaScript
1
42
42
1
var Persons = [];
2
window.onload = () => {
3
4
var PersonHTMLElement = document.getElementById("person");
5
var AmountHTMLElement = document.getElementById("amount");
6
var TotalHTMLElement = document.getElementById("total");
7
var PersonListHTMLElement = document.getElementById("final");
8
var TotalDividedHTMLElement = document.getElementById("aporte");
9
10
document.getElementById("calc").addEventListener("click", setPerson);
11
12
function setPerson(){
13
14
let person = PersonHTMLElement.value;
15
let amount = AmountHTMLElement.value;
16
17
Persons.push({
18
Name:person,
19
Amount:parseFloat(amount)
20
});
21
22
PersonHTMLElement.value = "";
23
AmountHTMLElement.value = "";
24
25
setTotal();
26
}
27
function setTotal(){
28
29
TotalHTMLElement.innerHTML = "";
30
31
let PersonsList = "";
32
let Total = 0;
33
for(let i = 0;i < Persons.length; i++){
34
Total += Persons[i].Amount;
35
PersonsList += `${Persons[i].Name}: ${Persons[i].Amount} <br>`;
36
}
37
38
TotalHTMLElement.innerHTML = PersonsList;
39
PersonListHTMLElement.innerHTML = Total;
40
TotalDividedHTMLElement.innerHTML = Total / Persons.length;
41
}
42
}
JavaScript
1
23
23
1
<html>
2
<head>
3
<script src="myscript.js"></script>
4
</head>
5
<body>
6
<h1>Expenses app</h1>
7
<p>Enter how much each person spent</p>
8
9
<p>Nombre</p>
10
<input type="text" id="person">
11
<br>
12
<p>Monto</p>
13
<input type="number" id="amount">
14
<br>
15
<br>
16
<button id="calc">Enviar</button>
17
<br>
18
<p>Total: <span id="final"></span> </p>
19
<div id="total">
20
</div>
21
<p>A cada uno le toca aportar: <span id="aporte"></span></p>
22
</body>
23
</html>