Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
john larson
16,594 PointsSeems like it should be simple...prompt for data using a function, push it to an array
when the page loads, it calls addItem(), which I don't get cause I'm calling it with a button...I enter some input it pushes that to the array and prints to the page. When I click again, the prompt appears- I enter data but nothing else get pushed to the array??? It may be sleep deprivation. I'm just playing with stuff to understand, but I need insight. Thank you :D
<button onclick = addItem()>Click to enter an item</button>
function print(output){
document.getElementById("display").innerHTML = output;
}
function addItem(){
var item = prompt("What would you like to add?");
return item;
}
var shoppingList = [];
shoppingList.push(addItem());
var html = "<ol>";
for(var i = 0; i < shoppingList.length; i += 1){
html += "<li>" + shoppingList[i] + "</li>";
}
html += "</ol>";
print(html);
1 Answer
Benjamin Barslev Nielsen
18,958 PointsWhen loading your JavaScript file you call addItem here:
shoppingList.push(addItem());
This line could simply be removed from your code, since the shoppingList initially should be empty.
The reason you don't see an updated shoppingList is due to a problem with your addItem function. In this function the item is never added to the shoppingList, but instead it is returned, and afterwards never used. It should therefore be pushed to your shoppingList array. This however is not enough, since the HTML also needs to be redrawn, so i purpose creating a function printShoppingList, which recalculates the HTML and then prints it to the screen. Then in addItem() you first add the item to the shoppingList and then call printShoppingList:
function addItem(){
var item = prompt("What would you like to add?");
shoppingList.push(item);
printShoppingList();
}
var shoppingList = [];
function printShoppingList() {
var html = "<ol>";
for(var i = 0; i < shoppingList.length; i += 1){
html += "<li>" + shoppingList[i] + "</li>";
}
html += "</ol>";
document.getElementById("display").innerHTML = html;
}
john larson
16,594 PointsIncidentally, I really like how you used the word purpose as opposed to propose. Very nice.
john larson
16,594 Pointsjohn larson
16,594 PointsBen, thank you so much for that well organized answer.