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
<span id="foo">
</span>
Javascript
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() {
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.