create and populate with DOM a checkbox list with array values in javascript

arrays, html, javascript

Solution

Here's one way (pure JavaScript, no jQuery):

var animals = ["lion", "tigers", "bears", "squirrels"];

var myDiv = document.getElementById("cboxes");

for (var i = 0; i < animals.length; i++) {
    var checkBox = document.createElement("input");
    var label = document.createElement("label");
    checkBox.type = "checkbox";
    checkBox.value = animals[i];
    myDiv.appendChild(checkBox);
    myDiv.appendChild(label);
    label.appendChild(document.createTextNode(animals[i]));
}

https://jsfiddle.net/lemoncurry/5brxz3mk/

Problem

I have an array of animals ... how do I manage to create a checkbox list in javascript and fill each with a name of the animals who are in animals array and display them in html. My my attempt code: ``` var lengthArrayAnimals = animals.length; for (var i= 0; pos < tamanhoArrayDiagnosticos; pos++) { var checkBox = document.createElement("input"); checkBox.setAttribute("type", "checkbox"); checkBox.name = diagnosticos[i]; } ```

Original source