How to create list of checkboxes dynamically with javascript

前端 未结 2 1919
南旧
南旧 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 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

    before you populate it:

    // clear the former content of a given 
    document.getElementById('some_div').innerHTML = '';

提交回复
热议问题