0

How to document.write() String from array, using for loop that will check if the checkboxes are selected. My example down isn't working. It works manually without for loop, so I assume that the problem is in loop.

<div style="width:100%"><input type="checkbox" id="cb1"></div>
<div style="width:100%"><input type="checkbox" id="cb2"></div>
<div style="width:100%"><input type="checkbox" id="cb3"></div>
<div style="width:100%"><input type="submit" id="execute" value="Execute" onClick="run();"></div>

submit.js

function run() {
    myArr = [" ","You selected first checkbox", "You selected second checkbox", "You selected the last one"];

    snip = "<div>HERE GOES YOUR CHECKBOX CHOICE: </div>";

    for(m=1;m<4;m++) {
    if(document.getElementById("cb[m]").checked == true) {
        snip += "<br/> - " + myArr[m];
    }
    document.write(snip);
}
}
1
  • 2
    Do you realize that once the current document has been loaded, any subsequent document.write() statements will clear the current document and start a new empty document? Commented Feb 26, 2014 at 17:53

1 Answer 1

3

m should be concatinated like ("cb" + m) not ("cb[m]")

Should be :

if(document.getElementById("cb" + m).checked == true) {    

Instead of :

if(document.getElementById("cb[m]").checked == true) {

I think you want to write this statement from outside of for loop

document.write(snip);

Suggestion

Also you can use innerHTML instead of document.write() as its clear other content after loaded the document.

innerHTML DEMO

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

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.