8

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];
}
1
  • You have to append the checkBox to the DOM Commented Feb 23, 2015 at 16:17

2 Answers 2

8

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/

Sign up to request clarification or add additional context in comments.

1 Comment

super. This helps a lot.
5

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.