Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to create a checkbox dynamically using following html/javascript. Any ideas why it doesnt work?

<html>
<head>
</head>
<body>
<div id="cb"></div>
<script type="text/javascript">
    var cbh = document.getElementById('cb');
    var val = '1';
    var cap = 'Jan';

    var cb = document.createElement('input');
    cb.type = 'checkbox';
    cbh.appendChild(cb);
    cb.name = val;
    cb.value = cap;
    cb.appendChild(document.createTextNode(cap));
</script>
</body>
</html>
share|improve this question
add comment (requires an account with 50 reputation)

3 Answers

up vote 15 down vote accepted

You're trying to put a text node inside an input element.

Input elements are empty and can't have children.

...
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "id";

var label = document.createElement('label')
label.htmlFor = "id";
label.appendChild(document.createTextNode('label');

container.appendChild(checkbox);
container.appendChild(label);
share|improve this answer
2  
Note that in some flavors of IE, the checkbox.checked value won't stick unless you set it AFTER the control's been appended to the page. – ajax81 Apr 14 '11 at 22:13
add comment (requires an account with 50 reputation)

The last line should read

cbh.appendChild(document.createTextNode(cap));

Appending the text (label?) to the same container as the checkbox, not the checkbox itself

share|improve this answer
add comment (requires an account with 50 reputation)

You can create a function:

function changeInputType(oldObj, oTyp, nValue) {
  var newObject = document.createElement('input');
  newObject.type = oTyp;
  if(oldObj.size) newObject.size = oldObj.size;
  if(oldObj.value) newObject.value = nValue;
  if(oldObj.name) newObject.name = oldObj.name;
  if(oldObj.id) newObject.id = oldObj.id;
  if(oldObj.className) newObject.className = oldObj.className;
  oldObj.parentNode.replaceChild(newObject,oldObj);
  return newObject;
}

And you do a call like:

changeInputType(document.getElementById('DATE_RANGE_VALUE'), 'checkbox', 7);
share|improve this answer
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.