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

前端 未结 2 1553
误落风尘
误落风尘 2021-01-13 02:25

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

相关标签:
2条回答
  • 2021-01-13 03:18

    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>

    0 讨论(0)
  • 2021-01-13 03:27

    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/

    0 讨论(0)
提交回复
热议问题