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

How can I place a checkbox in front of each value that is printed to my html view from a Javascript for in loop?

Heres a link to my Github Gist, for some reason I can't post my code in this forum

https://gist.github.com/TheC0mposer/ea1aea21a57f9218c00f

2 Answers

Here's one way to do it, assuming the values you want to print are in an array, and there is an element on the page with an id equal to result:

var values = ["first", "second", "third"];
var result = "";
function printArray() {
    for (i = 0; i < values.length; i++) { 
        result += "<input type='checkbox' name=" + values[i] + " value=" + values[i] + ">" + values[i] + "<br>";
    }
    document.getElementById("result").innerHTML = result;
}
printArray();

For demo purposes I used the value from the array for the name and value attributes, but, of course, you can change those to anything your app needs.

AHHH!!! I so wish I thought of
result += "<input type='checkbox' name=" + values[i] + " value=" + values[i] + ">" + values[i] + "<br>";
That makes so much sense. Thank you jcorum !!