Item Name Whe" /> Item Name Whe" /> Item Name Whe"/>

List.js - filtering by an attribute with more than 1 key/value/answer

386 views Asked by At

I'm trying to filter a List.js list by a data-attribute where the result has multiple answers:

 <div data-colors="red, blue, green">Item Name</div>

When I try the following it wont search through each item:

 $('.filter').on('click',function(){
   var $q = $(this).attr('data-colors');

   if($(this).hasClass('active')){
      myList.filter();
      $('.filter').removeClass('active');
   } else {
     myList.filter(function(item) {
        if (item.values().colors == $q) {
           return true;
        } else {
           return false;
        }
      });
      $('.filter').removeClass('active');
      $(this).addClass('active');
   }
});

If I try it when there is only one result, then it works fine:

 <div data-colors="red">Item Name</div>

I have tried various options to filter through each item, but nothing seems to work.

Any ideas?

1

There are 1 answers

0
zipzit On

I just did this analysis for a customer's project. We wanted a simple checkbox input system. The dilemma was individual elements within the Unordered list could have multiple roles (data-colors). I chose a single binary value to represent this. The filter used a simple Bitwise AND function. This worked well.

Complete Code is here.

Demo, via CodeSandBox is here. Be sure to look at console logs to understand the filtering transactions.

Key functions are here:

        var teamKey = 16 + 8 + 4 + 2 + 1;

        function OnChangeCheckbox(checkbox, listObj) {
            if (checkbox.checked) {
                console.log("The check box is checked. " + checkbox.value);
                teamKey += parseInt(checkbox.value, 10);
            } else {
                console.log("The check box is not checked.");
                // remove value from teamArray
                teamKey -= parseInt(checkbox.value, 10);
            }
            console.log("teamKey: " + dec2bin(teamKey));
            listObj.filter(filterList);
        }

        function filterList(item) {
            console.log("indiv value: ", dec2bin(item.values().teams), " teamKey: ", dec2bin(teamKey) )
            console.log( "     Bitwise And: ", dec2bin(item.values().teams & teamKey));

            if (item.values().teams & teamKey) {  // the magic is here
                console.log("    pass: ", item.values().teams & teamKey);
                return true;
            } else {
                console.log("    fail: ", item.values().teams & teamKey);
                return false;
            }
        }

The list element <div class="teams">XX</div> would be hidden via CSS display: none; in use.