JSGrid Dependent Filters

by Danish Farman

HTML

<link rel="stylesheet" href="http://js-grid.com/css/jsgrid.min.css">
<link rel="stylesheet" href="http://js-grid.com/css/jsgrid-theme.min.css">
<script src="http://js-grid.com/js/jsgrid.min.js"></script>
<script src="http://underscorejs.org/underscore-min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.4/themes/redmond/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<div id="jsGrid"></div>

JavaScript

var db = {

  loadData: function(filter) {
    return $.grep(this.clients, function(client) {
      return (!filter.Country || client.Country === filter.Country) &&
        (!filter.State || client.State === filter.State);
    });
  }

};

window.db = db;

db.countries = [{
    Name: "",
    Id: 0,
    States: []
  },
  {
    Name: "United States",
    Id: 1,
    States: [1, 2]
  },
  {
    Name: "Canada",
    Id: 2,
    States: [3, 4]
  }
];

db.states = [{
    Id: 0,
    Name: ""
  },
  {
    Id: 1,
    Name: "A1"
  },
  {
    Id: 2,
    Name: "B1"
  },
  {
    Id: 3,
    Name: "A2"
  },
  {
    Id: 4,
    Name: "B2"
  }
];

db.clients = [{
    "Name": "Otto Clay",
    "Country": 1,
    "State": 1
  },
  {
    "Name": "Connor Johnston",
    "Country": 1,
    "State": 2
  },
  {
    "Name": "Lacey Hess",
    "Country": 2,
    "State": 3
  },
  {
    "Name": "Timothy Henson",
    "Country": 2,
    "State": 4
  }
];

$("#jsGrid").jsGrid({
  height: 300,
  width: "100%",

  filtering: true,
  autoload: true,

  controller: db,

  fields: [{
    name: "Name",
    type: "textarea",
    width: 150
  }, {
    name: "Country",
    type: "select",
    items: db.countries,
    valueField: "Id",
    textField: "Name",
    filterTemplate: function() {
      var statesField = this._grid.fields[2];
      var $filterControl = jsGrid.fields.select.prototype.filterTemplate.call(this);

      $filterControl.on("change", function() {
        var selectedCountry = parseInt($(this).val(), 10);
        var countryStates = $.grep(db.countries, function(country) {
          return country.Id === selectedCountry;
        })[0].States;

        statesField.items = $.grep(db.states, function(state) {
          return $.inArray(state.Id, countryStates) > -1 || state.Id === 0;
        });

        $(".states-filter").empty()
          .append(statesField.filterTemplate());
      });

      return $filterControl;
    }
  }, {
    name: "State",
    type: "select",
    items: db.states,
   ...