I figured this next step would be simple but I've been pulling my hair out trying to figure it out. I am putting in an amount of money spent and inputting it via a submit button. As I am putting in multiple values (since I'm also making a list of what the money was spent on) I am trying to get a total of all the money spent, but I either get NaN or just nothing. In theory I am hoping that every time I would hit confirm, the amount of money in the text box would be added to the total for that day.
I've been trying to push the value in an array, then summing it with a for loop but perhaps I'm making this more complicated than it needs to be. Here's my code:
function totalSpent() {
var total= 0;
var spent = document.getElementById("moneySpent").value;
var array = [];
// check if the entered value is number
if (isNaN(Number(spent))) {
alert("Numbers only");
} else {
var spent = parseInt(document.getElementById("moneySpent").value);
for (var i=0; i<spent.length;++i){
array.push(parseFloat(spent[i].value));
}
total = array.reduce(function(previousValue, currentValue, index, array){
return previousValue + currentValue;
});
youSpent.innerHTML=`Total Spent Today: ${total}`;
}
}
<input type="amount" size=25 Placeholder="How much did you spend?"
id="moneySpent">
<input type="button" value="confirm" onClick="totalSpent()">
<br>
<h2 id="youSpent"> Total Spent Today:
</h2>
parseIntreturns a number... you can't do.lengthon a numbertotal += +items[item] ...and thendocument.getElementById("totalSpent").textContent = "Total $"+total.toFixed(2)see your other question and delete this