Choxmi Choxmi - 1 year ago 82
Javascript Question

create checkboxes dynamically in JavaScript

I'm trying to create check boxes dynamically. But I have no idea what is the wrong with this code. Somebody please help. Comment if you need more details.

$.getJSON(url, function(json) {

for (var i = 0; i < json.items.length; i++) {


var checkbox = document.createElement('input');
checkbox.type = "checkbox"; = "name" + json.items[i].name;
checkbox.value = "value"; = "id" + i;

Thank you


You never seem to be appending those dynamically created checkboxes to your DOM, so this checkbox variable that you create inside the loop simply gets garbage collected. If you want those checkboxes to appear somewhere make sure that you are actually adding them to the DOM:


Of course instead of simply appending them to the body of the DOM you might want to append them to some specific element in which case you might need to get this element first:

var someDiv = document.getElementById('someId');

or if you are using jQuery:

for (var i = 0; i < json.items.length; i++) {
    $('<input />', {
        type : 'checkbox',
        id: 'id' + i,
        name: 'name' + json.items[i].name,
        value: 'value'

where you obviously have the corresponding container to harbor those newly added elements:

<div id="someId"></div>