Javascript 如何在javascript中动态创建标签和复选框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7608266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:52:59  来源:igfitidea点击:

How to create label and check box dynamically in javascript?

javascript

提问by nirmal10

I want to create label and check box dynamically. when i enter text in text box and give submit button,a check box and label with the text i entered in text box should be created..How to create ?

我想动态创建标签和复选框。当我在文本框中输入文本并提供提交按钮时,应创建一个复选框和带有我在文本框中输入的文本的标签。如何创建?

回答by Dinkheller

For the label try this:

对于标签试试这个:

var newlabel = document.createElement("Label");
newlabel.setAttribute("for",id_from_input);
newlabel.innerHTML = "Here goes the text";
parentDiv.appendChild(newlabel);

回答by Irfan

I think you want this..

我想你想要这个..

//html
<div id="container">
<input id="test" type="text"  >
<input value="add" type="button"  onClick="add()">
</div>

//js
<script>
var i=0;
function add(){    
    if (document.getElementById('test').value!='') 
    {   
        i++;  
        var title   =document.getElementById('test').value;
        var node = document.createElement('div');        
        node.innerHTML = '<input type="checkbox" id="check' + i + '" name="check' + i + '"><label for="check' + i + '">'+ title +'</label>';       
        document.getElementById('container').appendChild(node);    
    }
}
</script>