Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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];
}
like image 572
Mario Medeiros Avatar asked Feb 23 '15 16:02

Mario Medeiros


2 Answers

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/

like image 198
Michael Dziedzic Avatar answered Oct 18 '22 00:10

Michael Dziedzic


I hope this is what you expected.

$(document).ready(function(){
var animals=["cat","dog","pikachu","charmaner"];

$.each(animals,function(index,value){
	var checkbox="<label for="+value+">"+value+"</label><input type='checkbox' id="+value+" value="+value+" name="+value+">"
	$(".checkBoxContainer").append($(checkbox));
})

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="checkBoxContainer"></div>
like image 43
roshan Avatar answered Oct 18 '22 00:10

roshan