How to create list of checkboxes dynamically with javascript

前端 未结 2 1920
南旧
南旧 2020-12-09 06:19

UPDATE: Code has been updated per Dan\'s comments.

I have a problem with a project I\'m working on. I need to create a list of checkboxes depending on what is select

相关标签:
2条回答
  • 2020-12-09 06:51

    A checkbox is a simple input element with type='checkbox'. So you have to prepare at least two things: a text node for the description of the box and the box itself. In this case it's also good to use a <label> element to include both things mention before:

    // create the necessary elements
    var label= document.createElement("label");
    var description = document.createTextNode(pair);
    var checkbox = document.createElement("input");
    
    checkbox.type = "checkbox";    // make the element a checkbox
    checkbox.name = "slct[]";      // give it a name we can check on the server side
    checkbox.value = pair;         // make its value "pair"
    
    label.appendChild(checkbox);   // add the box to the element
    label.appendChild(description);// add the description to the element
    
    // add the label element to your div
    document.getElementById('some_div').appendChild(label);
    

    You have to do the steps above for every pair. Note that you have to clear the given <div id="some_div"></div> before you populate it:

    // clear the former content of a given <div id="some_div"></div>
    document.getElementById('some_div').innerHTML = '';
    
    0 讨论(0)
  • 2020-12-09 06:52

    The process of creating a checkbox dynamically is indeed a little more involved than creating a select option. You need to create:

    • the checkbox
    • its label
    • and possibly a <br> for styling

    Here's the gist of the code, with the full fiddle at http://jsfiddle.net/dandv/9aZQF/2/:

    for (var option in optionArray) {
        if (optionArray.hasOwnProperty(option)) {
            var pair = optionArray[option];
            var checkbox = document.createElement("input");
            checkbox.type = "checkbox";
            checkbox.name = pair;
            checkbox.value = pair;
            s2.appendChild(checkbox);
    
            var label = document.createElement('label')
            label.htmlFor = pair;
            label.appendChild(document.createTextNode(pair));
    
            s2.appendChild(label);
            s2.appendChild(document.createElement("br"));    
        }
    }
    
    0 讨论(0)
提交回复
热议问题