Reputation: 29
I am trying to get user input and store it on an array but I can't seem to get the correct output, when I console log
the results I get different arrays with 0 length
Here's my code.
let bambooInputElement = document.querySelector('.bambooInputElement');
let bambooTotal = [];
function calculateBamboo() {
bambooInputElement = bambooInputElement.value;
if (bambooInputElement < 25) {
alert('Pledge must be at least $25.');
}else {
let amountDonated = 0;
for (let i = 0; i < bambooTotal.length; i++) {
bambooTotal.push(bambooInputElement);
amountDonated = amountDonated + bambooTotal[i];
}
}
}
bambooBtnElement.addEventListener('click', calculateBamboo);
Upvotes: 1
Views: 67
Reputation: 206111
bambooInputElement
is exactly what it says - and that's an Element, not its value - don't reassign types. Use a new variable instead.
Array.prototype.push() should be outside of the loop. Actually you don't need a for
loop at all, use Reduce.
Use Array.prototype.reduce() to reduce an array to a single value (the total amount)
Use return
inside a function to return a result / or an alert - if that's what you want.
const bambooInputElement = document.querySelector('.bambooInputElement');
const bambooBtnElement = document.querySelector('.bambooBtnElement');
const bambooDonations = []; // this is not total, those are donations!
function calculateBamboo() {
const val = parseFloat(bambooInputElement.value);
if (val < 25) return alert('Pledge must be at least $25.');
// Add to array of donations
bambooDonations.push(val);
// Get total donations
const totalDonations = bambooDonations.reduce((a, v) => a+=v, 0);
// Reset input value
bambooInputElement.value = "";
console.log(totalDonations); // TEST ONLY
// return that total:
return totalDonations;
}
bambooBtnElement.addEventListener('click', calculateBamboo);
<input type="number" class="bambooInputElement">
<button type="button" class="bambooBtnElement">CALCULATE</button>
Upvotes: 2
Reputation: 182
The line bambooTotal.push(bambooInputElement)
should be before the for loop. This is because, without pushing an element in the array, the length will always be zero hence it won't enter in the array.
Putting that line out of the for loop will ensure that the value get's entered and then the array is of atleast length 1.
Upvotes: 0