Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to dynamically create checkboxes based on multiple attributes from div

I would like for jQuery to dyanmically create a list of checkboxes based on the class/data present in divs. Essentially these checkboxes will filter through the products so that clicking a checkbox will show the products containing that tag in their div while avoiding any duplicate checkboxes.

Sample:

<div class="Shoes" data-size="Small" data-color="Black">
     <h3>Nike</h3>
</div>
<div class="Belts" data-size="Medium" data-color="Black">
     <h3>Belt</h3>
</div>
<div class="Shirt" data-size="Large" data-color="Blue">
     <h3>Polo</h3>
</div>
<div class="Socks" data-size="Small" data-color="White">
     <h3>Generic Socks</h3>
</div>

Expected output Class Type

  • Shoes
  • Belts
  • Shirt
  • Socks

Size

  • Small
  • Medium
  • Large

Color

  • Black
  • White
  • Blue

Each checkbox needs to be able to hide/show the item.

JsFIDDLE

The code I have so far is from searching around/previous answers, however it is only creating 1 checkbox type which is for "class" and not creating multiple ones.

like image 313
Dillon1998 Avatar asked Nov 01 '22 15:11

Dillon1998


1 Answers

Try

jQuery(function ($) {

    function createCheckboxes($els, attr) {
        var props = {};
        $els.each(function () {
            props[$(this).attr(attr)] = true;
        });

        return $.map(props, function (val, key) {
            var $chk = $('<input />', {
                type: 'checkbox',
                value: key
            })
            return $('<label />', {
                text: key
            }).append($chk)
        })
    }

    $('span').append(createCheckboxes($('div'), 'class'))
    $('span').append(createCheckboxes($('div'), 'data-size'))
    $('span').append(createCheckboxes($('div'), 'data-color'))
});

Demo: Fiddle

like image 67
Arun P Johny Avatar answered Nov 10 '22 15:11

Arun P Johny