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


js array help

I cannot figure out why when I click on my buttons only the last value in my array is showing up. I have three buttons in my html file. A peperoni, a taco, and a cheese. In the js file, in and array, I have the toppings and price. When i click on a button it's suppose to give me back the total for the topping, the pizza, and taxes. But only the cheese total shows up. Why?
Also this project is not complete and it's something i'm doing for practice/fun

var pizza = 10.00; var taxes = 0.06; var array = [ ['pep', 1.99], ['taco', 2.99], ['cheese', 0.99] ]; var topping; var cost; var total;

for (var i = 0; i < array.length; i++){ topping = array[i][0]; cost = array[i][1]; }

$('button').on('click', function(){ var get = $(this).attr('id'); if(get === topping){ total = pizza + taxes + cost;

} });

2 Answers

Juan Martin
Juan Martin
14,335 Points

Hey Matthew!

Can you include the HTML as well?


<body> <div id='header'> <h1>Pizza Builder</h1> <h3>Pizza: $10.00</h3> </div>

    <h2 id='tHeader'>Toppings</h2>
    <div id='wrapper'>
        <li>Peperoni</li><button id='pep'>+</button>
        <li>Taco</li><button id='taco'>+</button>
        <li>Cheese</li><button id='cheese'>+</button>

     <div id='display'>

Seth Kroger
Seth Kroger
56,413 Points

In your for loop you aren't adding the costs of the items together. You are just replacing the previous cost with the cost of the next item.

In my for loop im not trying to add anything. i am declaring that the index [1] of the array is the cost i want to get. And the first position [0] is the topping. I want to add that all up later. When the user chooses(clicks) the toppings they want.

Seth Kroger
Seth Kroger
56,413 Points

I see better what you are trying to accomplish here. because you are just replacing the previous cost with the cost of the next item, and the cost is globally scoped, after the for loop the cost will always be the cost of the last item only. I'd suggest using a simple object of the costs instead of an array. That way you could lookup the cost the the name of the item.

I'll try that. Sorry I wasn't clear on what I was trying to do. Thank you so much for your help.