Use virtual select as input

Hello, I’m new to Observable via Quarto, and I find its native capabilities extraordinary. I’d like to take things a step further by integrating the Virtual Select library, which I really appreciate for creating custom select inputs. After many attempts, the only method I’ve found so far is the following, using an event listener and a mutable variable:

VirtualSelect.init({
  ele: '#vSelectCommune',
  search: true,
  multiple: false,
  placeholder: 'Please select a commune',
  options: myArrayofObjects
});

mutable selectedCommune = ({})

document.querySelector('#vSelectCommune').addEventListener('change', function() {
  mutable selectedCommune = {
    insee: this.value,
    insee_commune: this.value + '_' + this.getDisplayValue()
  };
});

Everything works, but I feel like I might be missing some key concepts of Observable despite my careful reading of the documentation and exemples. If you have any suggestions to make this code snippet more elegant or less verbose, I’d be very grateful!

Thank you in advance!

the bit your missing is views Introduction to views / Observable | Observable

although getting that plugin working was not easy due to how it was packaged anyway.

Cells notify other cells of a value change with an ‘input’ event, but the lib was using change, so we swapped that. Also it is more idiomatic for Observable to combine a UI with a data channel in a single cell called a view, so I did that.

2 Likes

Thank you very much! I had read the reference page carefully, but I had missed the adaptation to the context of the virtual select… Your example, which I am able to adapt, really clarifies things for me.

1 Like

Good evening, and thanks again for your help! Here’s some feedback on my tests… For Quarto enthusiasts, there’s a conflict with the cell-output-display class of a wrapping div (the dropdown menu doesn’t appear). To avoid this issue, remember to specify during initialization that the dropdown menu is at the body level, as shown in the following example:
viewof selectedCommune = VirtualSelect({
search: true,
multiple: false,
dropboxWrapper: “body”, // essential in Quarto
hideClearButton: true,
placeholder: ‘Please select a commune’,
options: communes_listV,
autoSelectFirstOption: true,
// selectedValue: “50003”,
maxWidth: “100%”
})

1 Like