0

I have the following function that dynamically creates a bunch of checkboxes:

var drawGroups = function(){
  var groups = document.getElementById("groups"); //groups element is a div
  groups.innerHTML = "";

  //groupList is an array containing strings
  for(var i in groupList){
    var groupName = groupList[i];

    var cb = document.createElement('input');
    cb.type = "checkbox";
    cb.checked = true; //this seems to do nothing
    groups.appendChild(cb);

    groups.innerHTML += groupName + "<br/>"
  }
}

Everything I read indicates cb.checked = true should check the checkbox, but it doesn't seem to do anything. How can I create the checkboxes in a checked state?

2 Answers 2

3

You need to set the defaultChecked property:

var groupList = ['foo','bar','baz','biz','boz'];

var drawGroups = function(){
  var groups = document.getElementById("groups"); //groups element is a div
  groups.innerHTML = "";

  //groupList is an array containing strings
  for(var i in groupList){
    var groupName = groupList[i];

    var cb = document.createElement('input');
    cb.type = "checkbox";
    cb.defaultChecked = true;
    groups.appendChild(cb);

    groups.innerHTML += groupName + "<br/>"
  }
}
drawGroups();
<div id="groups"></div>

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

Comments

0

You could use the method setAttribute:

cb.setAttribute('checked',  true);

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.