1

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?

Bluberry17
  • 21
  • 1
  • 6

2 Answers2

2

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.

Noob
  • 2,247
  • 4
  • 20
  • 31
  • The solution actually worked by using Google Chrome instead of Edge, which I've resorted to using for several reasons. Which means that Edge doesn't support let? – Bluberry17 Aug 24 '19 at 15:31
  • Sure! But what if I want to use Edge? This solution doesn't work with Edge or IE. – Bluberry17 Aug 24 '19 at 15:36
  • @Bluberry17 it's hard to say why it didn't work in Edge, there can be a lot of reasons. I'm not sure if i can help you with that. Checking developer console for errors would be my best guess in this case. – Noob Aug 24 '19 at 15:38
  • 1
    Edge should have support for let / const variable declarations, see here: https://caniuse.com/#search=let so there might be something else going on. – Tobias G. Aug 24 '19 at 15:40
  • it won't work in IE (seriously, who still uses that??), but this should definitely work in Edge – Robin Zigmond Aug 24 '19 at 15:44
0

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

Tobias G.
  • 341
  • 1
  • 8