Set source property of Handsontable dropdown option to the corresponding data value

18 Views Asked by At

I have a data array taken from ajax call as

    data=[ // all are dynamic values can vary
        ['Alex', '16', ['2024-01-01,50000', '2024-03-01,20000', '2024-05-01,30000']],
        ['Bob', '21', ['2022-02-01,50000', '2022-03-01,10000']],
        ['Jack', '20', ['2023-03-01,50000', '2023-04-01,60000', '2023-05-01,50000']],
        ['John', '18', ['2020-04-01,20000', '2020-05-01,50000', '2020-06-01,30000', '2020-07-01,50000']],
    ];

I need to create a dropdown for the 3rd column as an array representing the dates,amount in each dropdown in a basic javascript.

It's easy if the data is static but since it is made from the ajax call I cannot hardcode the source property of dropdown menu

It's a plain javascript Handsontable initialization.

Any help would be appreciated

I called a getSource function with query and callback parameter in source attribute like this:

    function getSource(query, callback) {
        var selectedRow = hotInstance.getSelected()[0][0];
        var options = data[selectedRow][2];
        callback(options);
    }

this gave me a problem that when i select a dropdown item it updates the dropdown menu for example, in the above data array, if i opened up the dropdown of the first row and select any random option(let's say option 2 i.e. '2024-03-01,20000'). this value is selected correctly. but again when i open up the same dropdown the dropdown items has 2024-03-01 as the first data and 20000 as second data rather than '2024-01-01,50000', '2024-03-01,20000', '2024-05-01,30000' these 3 options.

1

There are 1 best solutions below

0
ABudnik On

Would something like this work for you?

const rel = document.querySelector('.result');
const ht = document.querySelector('.ht');
const API = 'https://randomuser.me/api/?results=10';
let hot, data;

data = [
  {
    "First name": "Emma",
    "Last name": "Garcia",
    "E-mail": "[email protected]",
    "Country": "United States"
  },
  {
    "First name": "Noah",
    "Last name": "Hernandez",
    "E-mail": "[email protected]",
    "Country": "Canada"
  },
  {
    "First name": "Olivia",
    "Last name": "Gomez",
    "E-mail": "[email protected]",
    "Country": "Mexico"
  }
]  

hot = new Handsontable(ht, {
    data,
    colHeaders: ['First name', 'Last name', 'E-mail', 'Country'],
  rowHeaders: true,
  colWidths: [100, 100, 200, 150],
  licenseKey: 'non-commercial-and-evaluation'
})

fetch(API)
.then(response => {
    if(response.ok){
    return response.json()
  }
})
.then(data => {
  let mydata = data.results.map( person => (
     person.name.first
  ))
  console.log(mydata)
  hot.updateSettings({
     cells: (row, col) => {
      let cp = {}
      if(col === 0){
        cp.type = 'dropdown';
        cp.source = mydata
      }
      return cp
    }
  })
})