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);
2 Answers 2
bambooInputElementis 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
forloop at all, use Reduce.Use Array.prototype.reduce() to reduce an array to a single value (the total amount)
Use
returninside 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>
Comments
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.
bambooTotalis always zero and hence nothing is ever pushed into the list, bring thepushstatement outside of the for loop, and try to add clarifications to what you wanna do withamountDonatedtoo.bambooInputElement = bambooInputElement.value;is quite suspect. What isbambooInputElementto start with? Why are you replacing that initial value withbambooInputElement.value? The second time you callcalcualteBamboo,bambooInputElementwill be thebambooInputElement.valuefrom the previous call.bambooInputElementis the html input element hence I'm reassigning it,bambooInputElement = bambooInputElement.value;I want the value the user enters and push it on thebambooTotalarray when a button is clicked