Bluberry17
Bluberry17

Reputation: 21

How to add onclick functions in an array of buttons using a for loop properly?

I'm making a kind of HTML calculator to test something I have in mind. I've used a for loop to create the buttons of the keypad. The display is a text field. Then I used a for loop to add the functions in the buttons:

for (var i = 0; i < 10; i++)
{
    buttons[i].onclick = function()
    {
        display.value += i;
    };
}

What I was trying to do is to make, for example, buttons[0] add "0" to the value of the text field when clicked. Instead, clicking any button added "10" in the text field. Why? How can I make it right?

Upvotes: 1

Views: 2340

Answers (2)

Tobias G.
Tobias G.

Reputation: 341

Your problem is that you are referencing i directly in your functions that you are binding to your Buttons. i will actually continue to exist even after you bound all your events, and its value will be the last value of the iteration 10. So whenever a click function runs, it looks up i and finds the last value you set (10) and takes that value. What you want to do is add a constant reference instead - so that you bind that value you have during the loop and keep that reference forever, no matter how i might change later.

for (var i = 0; i < 3; i++) {
    const localValue = i
    buttons[i].onclick = function()
    {
        counter += localValue;
        counterElement.innerHTML = counter
    };
}

I created a small example fiddle here: https://jsfiddle.net/4k8cds9n/ if you run this you should see the buttons in action. Some related reading for this topic would be around scopes in javascript, one good article: https://scotch.io/tutorials/understanding-scope-in-javascript

Upvotes: 0

Noob
Noob

Reputation: 2807

You almost got it right , you just need to change var to let in your loop declaration :

 for (let i = 0; i < 10; i++)
{
    buttons[i].onclick = function()
    {
        display.value += i;
    };
}

What's the difference between using "let" and "var"? Here you can get more info about your issue.

Upvotes: 2

Related Questions