vellai durai vellai durai - 5 months ago 10
jQuery Question

Create checkbox list from related divs

I need to create number of checkbox based on the number of array values returned from jQuery. Here is my code:

<div class="bob" data-xyz="fish"></div>
<div class="bob" data-xyz="dog"></div>
<div class="bob" data-xyz="fish"></div>
<div class="bob" data-xyz="cat"></div>
<div class="bob" data-xyz="fish"></div>


Ineed to display the result value in HTML like this:

<label>
<input class="fish" type="checkbox" />
fish
</label>
<label>
<input class="cat" type="checkbox" />
cat
</label>
<label>
<input class="dog" type="checkbox" />
dog
</label>


This is what I tried:

var items = {};
$('div.bob').each(function() {
items[$(this).attr('data-xyz')] = true;
});

var result = new Array();
for(var i in items) {
result.push(i);
}
alert(result);

Answer

You could do this in two loops, one to create the array of items to create checkboxes for and other to create the checkboxes themselves:

var items = $.unique($('.bob').map(function() {
    return $(this).data('xyz');
}).get());

var html = '';
for (var i = 0; i < items.length; i++) {
    html += '<label><input  class="' + items[i] + '" type="checkbox" />' + items[i] + '</label>'
}
$('.checkboxes').append(html);

Example fiddle

Or you could do this in a single loop, creating the checkboxes as you go:

var html = '';
$('.bob').each(function() { 
    var item = $(this).data('xyz');
    if (!$('input.' + item).length)
        $('.checkboxes').append('<label><input class="' + item + '" type="checkbox" />' + item + '</label>');
});

Example fiddle

The former has the pro of making less calls to the DOM, but has to make two loops through the data.