Reputation: 91
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>';
}
}
Upvotes: 0
Views: 79
Reputation: 2372
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 i.e.
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;
Upvotes: 0
Reputation: 1722
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;
}
Upvotes: 1
Reputation: 121
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
}
Upvotes: 1