Creating the checkbox dynamically using JavaScript?

后端 未结 4 642
醉话见心
醉话见心 2020-11-30 06:10

I am trying to create a checkbox dynamically using following HTML/JavaScript. Any ideas why it doesn\'t work?

相关标签:
4条回答
  • 2020-11-30 06:52

    You can create a function:

    function changeInputType(oldObj, oTyp, nValue) {
      var newObject = document.createElement('input');
      newObject.type = oTyp;
      if(oldObj.size) newObject.size = oldObj.size;
      if(oldObj.value) newObject.value = nValue;
      if(oldObj.name) newObject.name = oldObj.name;
      if(oldObj.id) newObject.id = oldObj.id;
      if(oldObj.className) newObject.className = oldObj.className;
      oldObj.parentNode.replaceChild(newObject,oldObj);
      return newObject;
    }
    

    And you do a call like:

    changeInputType(document.getElementById('DATE_RANGE_VALUE'), 'checkbox', 7);
    
    0 讨论(0)
  • 2020-11-30 06:54
       /* worked for me  */
         <div id="divid"> </div>
         <script type="text/javascript">
             var hold = document.getElementById("divid");
             var checkbox = document.createElement('input');
             checkbox.type = "checkbox";
             checkbox.name = "chkbox1";
             checkbox.id = "cbid";
             var label = document.createElement('label');
             var tn = document.createTextNode("Not A RoBot");
             label.htmlFor="cbid";
             label.appendChild(tn); 
             hold.appendChild(label);
             hold.appendChild(checkbox);
          </script>  
    
    0 讨论(0)
  • 2020-11-30 07:13

    You're trying to put a text node inside an input element.

    Input elements are empty and can't have children.

    ...
    var checkbox = document.createElement('input');
    checkbox.type = "checkbox";
    checkbox.name = "name";
    checkbox.value = "value";
    checkbox.id = "id";
    
    var label = document.createElement('label')
    label.htmlFor = "id";
    label.appendChild(document.createTextNode('text for label after checkbox'));
    
    container.appendChild(checkbox);
    container.appendChild(label);
    
    0 讨论(0)
  • 2020-11-30 07:15

    The last line should read

    cbh.appendChild(document.createTextNode(cap));
    

    Appending the text (label?) to the same container as the checkbox, not the checkbox itself

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