0

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>';

     }

}
2
  • 2
    Change to: innerHTML += ... Commented Dec 5, 2015 at 5:34
  • you tried .append() function? Commented Dec 5, 2015 at 5:35

3 Answers 3

1

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

}
Sign up to request clarification or add additional context in comments.

3 Comments

I think it will replace content.
Ok, Its my mistake :)
I think @HarshSanghani meant that if #foo already has some content, calling init() will replace that content, which your code does. Try calling the function twice (viz. init(); init();). His code preserves the contents, however.
1

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;

}

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.