skip to Main Content

I am pretty new to JS and JQuery and I am trying to filter JSON data on a page using checkboxes. So far, I have gotten it to work for each checkbox selected. Except i have one problem. How can I make this code better so that say you select multiple checkboxes, it shows the data for both. Below is my code.

//filter data with checkboxes
$('#submitFilter').click(function() {
  var final = '';
  $('.filters:checked').each(function() {
    var values = $(this).val();
    final += values;
  });

  var globalFilterVariable = '';
  var categoryImage = '';

  $.each(product_data, function(i, item) {
    if (final.indexOf("1") >= 0) {
      globalFilterVariable = item.itemGlutenFree;
    } else if (final.indexOf("2") >= 0) {
      globalFilterVariable = item.itemGMOFree;
    } else if (final.indexOf("3") >= 0) {
      globalFilterVariable = item.itemOrganic;
    } else if (final.indexOf("4") >= 0) {
      globalFilterVariable = item.itemLowSodium;
    } else if (final.indexOf("5") >= 0) {
      globalFilterVariable = item.itemBPAFree;
    } else if (final.indexOf("6") >= 0) {
      globalFilterVariable = item.itemKosherSym;
    }

    //convert JSON strings to uppercase for comparison
    var brandLetter = item.itemBrandLetter.toUpperCase();
    var foodService = item.itemDeli.toUpperCase();

    if (globalFilterVariable !== "N" && globalFilterVariable !== "n" && globalFilterVariable !== "" && brandLetter == "C" && foodService == "N") {
      categoryImage += '<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12">' + '<a href="#"' + 'class="showProduct"' + 'data-itemcategory="' + item.itemCategory + '"' + 'data-itempageurl="' + item.itemFullUPC + '"' + 'data-itemgmo="' + item.itemGMOFree + '"' + 'data-itembpa="' + item.itemBPAFree + '"' + 'data-itemgluten="' + item.itemGlutenFree + '"' + 'data-itemlowsodium="' + item.itemLowSodium + '"' + 'data-itemkosher="' + item.itemKosherSym + '"' + 'data-itemorganic="' + item.itemOrganic + '"' + 'data-itemimage="' + item.imageURL + '"' + 'data-itemname="' + item.itemName + '"' + 'data-itemoz="' + item.itemPackSize + '"' + 'data-itemdescription="' + item.itemDescription + '"' + 'data-itemupc="' + item.itemFullUPC + '">' + '<img class="img-responsive img-hover productImagesCategory" src="' + item.imageURL + '">' + '<h3>' + item.itemName + '</h3>' + '</a>' + '</div>';
      console.log(globalFilterVariable);
    }
  });
  $('#imagesCategoryProducts').hide().html(categoryImage).fadeIn('slow');
  closeNav();
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-gulten" class="filters" value="1">Gluten Free</label>
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-non-gmo" class="filters" value="2">Non-GMO</label>
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-organic" class="filters" value="3">Organic</label>
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-low-sodium" class="filters" value="4">Low Sodium</label>
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-bpa-free" class="filters" value="5">BPA Free</label>
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-kosher" class="filters" value="6">Kosher</label>
  </div>
  <button type="button" id="submitFilter" class="btn btn-primary">Submit</button>
  <button type="button" id="clearFilter" class="btn btn-primary">Clear</button>
</form>
[
   {
      "_id":"57741c92cce3c4c741000002",
      "itemGMOFree":"Y",
      "itemBrandLetter":"C",
      "itemKosherSym":"OU",
      "itemShipper":"N",
      "itemRefridge":"N",
      "itemFrozen":"N",
      "itemPreWeight":"Y",
      "itemDeli":"N",
      "itemGlutenFree":"Y",
      "itemHoliday":"N",
      "itemSeasonBuy":"N",
      "itemScannable":"N",
      "itemUnlabeled":"N",
      "itemPalletWeight":2368.8,
      "itemPalletTiers":11,
      "itemPalletBlocks":17,
      "itemCaseCube":0.29,
      "itemCaseDepth":12,
      "itemCaseWidth":9,
      "itemCaseHeight":4.75,
      "itemCaseWeight":12.4,
      "itemCaseUnits":12,
      "itemPieceCube":0.02,
      "itemPieceDepth":2.88,
      "itemPieceWidth":2.88,
      "itemPieceHeight":4.25,
      "itemPieceWeight":1,
      "itemNetContent":"14",
      "itemFullUPC":"070796400032",
      "itemCountry":"Italy",
      "itemPackSize":"12/14 oz",
      "itemUOM":"OZ",
      "itemDescription":"0",
      "itemName":"test",
      "itemBuildNum":0,
      "itemSuffix":2,
      "itemItem":40003,
      "itemMFG":70796,
      "itemPrefix":0,
      "itemCase_GTIN":30,
      "itemPiece_GTIN":0,
      "imageURL":"test.jpg",
      "itemCommodity":"1120",
      "__v":0,
      "itemLastUpdated":"1/19/2017 9:56:16 AM",
      "itemVendor":0,
      "itemBPAFree":"Y",
      "itemLowSodium":"N",
      "itemOrganic":"N",
   }
]

3

Answers


  1. Not 100% sure what you are trying to accomplish, but you can change the value attributes of your checkboxes to store the name you want to lookup.

    You can then get all those checked-values and use them to lookup the filter you want. Not sure why your globalFilterVariable is a string, so I could not get too far. I only grabbed the zero-th element.

    // Filter data with checkboxes
    $('#submitFilter').click(function() {
      var filters = [];
      $('.filters').find(':checked').each(function() {
        filters.push($(this).val());
      });
    
      var globalFilterVariable = '';
      var categoryImage = '';
    
      $.each(product_data, function(i, item) {
        // Figure out what you want to do with the rest of the filters.
        globalFilterVariable = item[filters[0]]; 
       
        // Convert JSON strings to uppercase for comparison
        var brandLetter = item.itemBrandLetter.toUpperCase();
        var foodService = item.itemDeli.toUpperCase();
    
        if (['N', 'n', ''].indexOf(globalFilterVariable) === -1
              && brandLetter == "C" && foodService == "N") {
          categoryImage += '<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12">'
            + '<a href="#"' + 'class="showProduct" '
              + 'data-itemcategory="' + item.itemCategory + '" '
              + 'data-itempageurl="' + item.itemFullUPC + '" '
              + 'data-itemgmo="' + item.itemGMOFree + '" '
              + 'data-itembpa="'+ item.itemBPAFree + '" '
              + 'data-itemgluten="' + item.itemGlutenFree + '" '
              + 'data-itemlowsodium="' + item.itemLowSodium + '" '
              + 'data-itemkosher="' + item.itemKosherSym + '" '
              + 'data-itemorganic="' + item.itemOrganic + '" '
              + 'data-itemimage="' + item.imageURL + '" '
              + 'data-itemname="' + item.itemName + '" '
              + 'data-itemoz="' + item.itemPackSize + '" '
              + 'data-itemdescription="' + item.itemDescription + '" '
              + 'data-itemupc="' + item.itemFullUPC + '">'
            + '<img class="img-responsive img-hover productImagesCategory" src="' + item.imageURL + '">'
            + '<h3>' + item.itemName + '</h3>'
          + '</a>'
          + '</div>';
          console.log(globalFilterVariable);
        }
      });
      $('#imagesCategoryProducts').hide().html(categoryImage).fadeIn('slow');
      closeNav();
    });
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <form>
      <div class="checkbox">
        <label><input type="checkbox" class="filters"
                      name="filter-gulten" value="itemGlutenFree">Gluten Free</label>
      </div>
      <div class="checkbox">
        <label><input type="checkbox" class="filters"
                      name="filter-non-gmo" value="itemGMOFree">Non-GMO</label>
      </div>
      <div class="checkbox">
        <label><input type="checkbox" class="filters"
                      name="filter-organic" value="itemOrganic">Organic</label>
      </div>
      <div class="checkbox">
        <label><input type="checkbox" class="filters"
                      name="filter-low-sodium" value="itemLowSodium">Low Sodium</label>
      </div>
      <div class="checkbox">
        <label><input type="checkbox" class="filters"
                      name="filter-bpa-free" value="itemBPAFree">BPA Free</label>
      </div>
      <div class="checkbox">
        <label><input type="checkbox" class="filters"
                      name="filter-kosher"  value="itemKosherSym">Kosher</label>
      </div>
      <button type="button" id="submitFilter" class="btn btn-primary">Submit</button>
      <button type="button" id="clearFilter" class="btn btn-primary">Clear</button>
    </form>

    Here is a much simpler approach to understand how to filter a list of objects by their keys.

    If you want only items that match EXTACTLY what you check-off, use this expression instead:

    var filteredItems = sampleItems.filter(function(item) {
      return availableFilters.every(function(filter) {
        return !!item[filter] === activeFilters.indexOf(filter) > -1;
      });
    });
    
    var sampleItems = [{
      name : "All",
      gmoFree : 'Y',
      bpaFree : 'Y',
      glutenFree : 'Y',
      lowSodium : 'Y',
      kosherSym : 'Y',
      organic : 'Y'
    }, {
      name : "None",
      gmoFree : 'N',
      bpaFree : 'N',
      glutenFree : 'N',
      lowSodium : 'N',
      kosherSym : 'N',
      organic : 'N'
    }, {
      name : "GMO and Gluten Free",
      gmoFree : 'Y',
      bpaFree : 'N',
      glutenFree : 'Y',
      lowSodium : 'N',
      kosherSym : 'N',
      organic : 'N'
    }];
    
    $('#submitFilter').click(function() {
      var availableFilters = [];
      var activeFilters = [];
      var $filters = $('.filters').each(function() {
        var value = $(this).val();
        availableFilters.push(value);
        if ($(this).is(':checked')) {
          activeFilters.push(value);
        }
      });
      var filteredItems = sampleItems.filter(function(item) {
        return availableFilters.every(function(filter) {
          if (activeFilters.indexOf(filter) > -1) {
            return item[filter] === 'Y';
          }
          return true;
        });
      });
      var $list = $('#list').empty();
      $.each(filteredItems, function(index, item) {
        $list.append($('<LI>').text(JSON.stringify(item)));
      });
    });
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <form>
      <div class="checkbox">
        <label><input type="checkbox" class="filters"
                      name="filter-gulten" value="glutenFree">Gluten Free</label>
      </div>
      <div class="checkbox">
        <label><input type="checkbox" class="filters"
                      name="filter-non-gmo" value="gmoFree">Non-GMO</label>
      </div>
      <div class="checkbox">
        <label><input type="checkbox" class="filters"
                      name="filter-organic" value="organic">Organic</label>
      </div>
      <div class="checkbox">
        <label><input type="checkbox" class="filters"
                      name="filter-low-sodium" value="lowSodium">Low Sodium</label>
      </div>
      <div class="checkbox">
        <label><input type="checkbox" class="filters"
                      name="filter-bpa-free" value="bpaFree">BPA Free</label>
      </div>
      <div class="checkbox">
        <label><input type="checkbox" class="filters"
                      name="filter-kosher"  value="kosherSym">Kosher</label>
      </div>
      <button type="button" id="submitFilter" class="btn btn-primary">Submit</button>
      <button type="button" id="clearFilter" class="btn btn-primary">Clear</button>
    </form>
    <h2>Results</h2>
    <ul id="list"></ul>
    Login or Signup to reply.
  2. Don’t know what you’re trying to do here but you can make the loop more efficient by replacing the value by the item name

        <form>
      <div class="checkbox">
        <label>
          <input type="checkbox" id="filter-gulten" class="filters" value="itemGlutenFree">Gluten Free</label>
      </div>
      <div class="checkbox">
        <label>
          <input type="checkbox" id="filter-non-gmo" class="filters" value="itemGMOFree">Non-GMO</label>
      </div>
      <div class="checkbox">
        <label>
          <input type="checkbox" id="filter-organic" class="filters" value="itemOrganic">Organic</label>
      </div>
      <div class="checkbox">
        <label>
          <input type="checkbox" id="filter-low-sodium" class="filters" value="itemLowSodium">Low Sodium</label>
      </div>
      <div class="checkbox">
        <label>
          <input type="checkbox" id="filter-bpa-free" class="filters" value="itemBPAFree">BPA Free</label>
      </div>
      <div class="checkbox">
        <label>
          <input type="checkbox" id="filter-kosher" class="filters" value="itemKosherSym">Kosher</label>
      </div>
      <button type="button" id="submitFilter" class="btn btn-primary">Submit</button>
    

    Clear

    and use simple loop to get the item keys

        $('#submitFilter').click(function() {
      var final = [];
      $('.filters:checked').each(function() {
        var values = $(this).val();
        final.push(values);
      });
      for(var i=0;i<final.length,i++){
        globalFilterVariable = item[final[i]];
       //further statements
      }
    });
    
    Login or Signup to reply.
  3. Check out the following fiddle : https://jsfiddle.net/bxoahfum/

    no need for jquery… I hope that its in the right direction.

    HTML

    <input data-filter="gluten"  type="checkbox"> Gluten<br/>
    <input data-filter="organic" type="checkbox"> Organic<br/>
    <input data-filter="bpa"     type="checkbox"> BPA Free<br/>
    
    <button id="filter">Filter!</button>
    
    <div id="results"></div>
    

    JS

    var items = [
      { name : 'product 1', gluten : true, organic : true, bpa : false },
      { name : 'product 2', gluten : true, organic : false,bpa : true  },
      { name : 'product 3', gluten : true, organic : true, bpa : true  }
    ];
    
    var filters = ['gluten','organic','bpa'];
    
    filter.onclick = function(){
    
      results.innerHTML = '';
    
      items.forEach(function(item){
    
        var show = true;
    
        filters.forEach(function(filter){
    
          $el = document.querySelector('[data-filter="'+filter+'"]');
          if($el.checked && !item[filter]) show = false;
    
        });
    
        if(show){
          $result = document.createElement('div');
          $result.innerHTML = item.name;
          results.appendChild($result);
        }
    
      });
    };
    

    it’s kosher

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search