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

前端 未结 2 1554
误落风尘
误落风尘 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: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/

提交回复
热议问题