views:

2572

answers:

2

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>
+4  A: 

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);
David Dorward
A: 

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

David Caunt