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

JavaScript

Add buttons and alert its current index value

I'm playing around with JavaScript and am trying to add 15 buttons on the screen and alert its current index value when clicked.

I'm using the for loop in order to add the buttons. How can I add the buttons and show it's current index value from 1 instead of 0 and alert its index value?

function printButton() {
  for(i=0; i<15; i++) {
    var myButton = '<button onclick="alert(i)">' + i + '</button> <br/>';
    document.write(myButton);
  }
}
printButton();

2 Answers

I tested the above code, wasn't working as intended (all buttons were alerting 16). Made a small tweak to output the correct number.

function printButton() {
    for (var i = 1; i < 16; i++) {
        var myButton = '<button onclick="alert(' + i + ')">' + i + '</button> <br/>';
        document.write(myButton);
    }
}
printButton();

Thank you guys! Yeah that makes more sense now. Would you mind if I ask why you use: + (i + 1) + on the alert() ?

Something like this should work:

function printButton() {
  for(i=0; i<15; i++) {
    var myButton = '<button onclick="alert(i + 1)">' + (i + 1) + '</button> <br/>';
    document.write(myButton);
  }
}
printButton();

correction to fix the alert issue mentioned (However Alec's answer is cleaner)

function printButton() {
  for(i=0; i<15; i++) {
    var myButton = '<button onclick="alert(' + (i + 1) + ')">' + (i + 1) + '</button> <br/>';
    document.write(myButton);
  }
}
printButton();