Change dropdown values based on a selection of another dropdown using Jexcel

1k Views Asked by At

I'm using Jexcel spreadsheet to catalog some data from a survey.

In a column I have a dropdown with vehicle manufacturers as options (Toyota, Honda ...).

In another column I have another dropdown with vehicle models.

How do I filter the models only from the manufacturer selected in the first dropdown?

The data structure is something like:

var manufacturers = [
  { id: 1, name: 'Toyota' },
  { id: 2, name: 'Honda' }
];

var models = [
  { id: 8, manufacturer_id: 1, name: 'Corolla' },
  { id: 9, manufacturer_id: 2, name: 'Civic' }
];
1

There are 1 best solutions below

0
On
  1. set the column sources.
  2. point the filter property of the "model" column to a function that will be used to filter the content dropdownFilter
  3. in that function we filter the source using the id, manufacturer_id and source.filter()

Here's a Working Pen

var manufacturers = [
  { id: 1, name: "Toyota" },
  { id: 2, name: "Honda" }
];

var models = [
  { id: 8, manufacturer_id: 1, name: "Corolla" },
  { id: 9, manufacturer_id: 2, name: "Civic" },
  { id: 10, manufacturer_id: 2, name: "Accord" }
];

var options = {
  minDimensions: [2, 5],
  columns: [
    {
      type: "dropdown",
      title: "Manufacturer",
      width: "150",
      source: manufacturers
    },
    {
      type: "dropdown",
      title: "Model",
      width: "150",
      source: models,
      // this is where the magic happens :)
      filter: dropdownFilter
    }
  ],
};


var mySpreadsheet = $("#spreadsheet").jexcel(options);


function dropdownFilter(instance, cell, c, r, source) {
  //get the manufacturer_id from the previus column
  var manufacturer_id = instance.jexcel.getValueFromCoords(c - 1, r);
  
  if (manufacturer_id !== "") {
    // if a manufacturer is selected filter source using its id
    return source.filter(function (item) {
      if (item.manufacturer_id == manufacturer_id) return true;
    })
  } else {
    //if no manufacturer is selected return an empty array
    return [];
    // or uncomment the following line to return the full source
    // return source
  }
}