简体   繁体   English

根据数组值动态添加复选框

[英]dynamically add check boxes based upon array value javascript

I have the following code and i would like to add check boxes based upon an array of values: 我有以下代码,我想基于值数组添加复选框:

When i run the code it replaces the check box instead of appending a new one. 当我运行代码时,它将替换复选框,而不是附加一个新复选框。

HTML 的HTML

   <span id="foo">


           </span>

Javascript Java脚本

function init() {

    var values = ["value1", "Value2", "Value3", "Value4"];

     for (i = 0; i < values.length; i++) {
        document.getElementById("foo").innerHTML = '<label><input type="checkbox" value="' + values[i] + '_checkbox">' + values[i] + '</label><br>';

     }

}

You can try following code, 您可以尝试以下代码,

function init() {
    var str =''; //INitial a string
    var values = ["value1", "Value2", "Value3", "Value4"];

     for (i = 0; i < values.length; i++) {
       str +='<label><input type="checkbox" value="' + values[i] + '_checkbox">' + values[i] + '</label><br>'; //Append values in string

     }
document.getElementById("foo").innerHTML = str; //Assign string to element

}

You can do it by these way :- 您可以通过以下方式实现:

function init() {
    var str    = document.getElementById("foo").innerHTML;
    var values = ["value1", "Value2", "Value3", "Value4"];

     for (i = 0; i < values.length; i++) {
       str +='<label><input type="checkbox" value="' + values[i] + '_checkbox">' + values[i] + '</label><br>';

     }
document.getElementById("foo").innerHTML = str;

}

By this you get only last check box function init() { 这样,您仅获得最后一个复选框函数init(){

    var values = ["value1", "Value2", "Value3", "Value4"];

     for (i = 0; i < values.length; i++) {
        document.getElementById("foo").innerHTML = '<label><input type="checkbox" value="' + values[i] + '_checkbox">' + values[i] + '</label><br>';

     }

}

So concatenate your result ie 所以连接您的结果即

for (i = 0; i < values.length; i++) {
      text   += '<label><input type="checkbox" value="' + values[i] + '_checkbox">' + values[i] + '</label><br>';

}
document.getElementById("foo").innerHTML = text;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM