Unlisted
Edited
Mar 18, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
viewof selection2
Insert cell
selection2
Insert cell
Insert cell
Inputs.button([
["Set to 1", () => set(viewof selection2, ["One"])],
["Set to 2,3", () => set(viewof selection2, ["Two","Three"])],
["clear", () => set(viewof selection2, [])]
])
Insert cell
function set(input, value) {
input.value = value;
// input.dispatchEvent(new CustomEvent("input", {bubbles: true}));
}
Insert cell
Insert cell
renderDropdown = (id) => {
// https://github.com/Choices-js/Choices
// https://talk.observablehq.com/t/getting-inputs-bind-to-work-on-a-custom-component/7756/5
// create a multi select element and add it to the DOM
const select = html`<select multiple></select>`
// initialise choices
let dropdown = new Choices(select, {
removeItemButton: true,
allowHTML: true,
choices: options
})
// set event listeners (adapted from https://observablehq.com/@mbostock/form-input)
const container = html`<div>${select.closest(".choices")}</div>`
// container.addEventListener("change", () => container.dispatchEvent(new CustomEvent("input")));
// container.addEventListener("input", () => container.value = Array.from(select, d => d.value));
// container.value = [];

function getValue() {
let currentValue = dropdown.getValue(true)
console.log(`get - id:[${id}] v:[${currentValue}]`)
return currentValue;
}
function setValue(newValue) {
let currentValue = container.value
console.log(`set - id:[${id}] c:[${currentValue}] n:[${newValue}]`)

if(currentValue.toString() !== newValue.toString()) {
console.log(`updating - id:[${id}] v:[${newValue}]`)

// ❌ why is this not updating when items are removed?
// it does update the values... but then gets into a
// loop where it "resets" the values to the current ones!?
// and only adds values??
dropdown.setChoiceByValue(newValue)
console.log(`updated - id:[${id}]`)
// This triggers the input event and it seems that
// that somehow overwrites the value that was just set
// container.dispatchEvent(new CustomEvent("change", {bubbles: true})); // this is needed to update the actual value of the container
// console.log(`dispatchedEvent id:[${id}]`)
}
}
Object.defineProperty(container, "value", {
get: getValue,
set: setValue
});
return container
}
Insert cell
options = [
{ value: "One", label: "Label one"},
{ value: "Two", label: "Label two" },
{ value: "Three", label: "Label three" }
]
Insert cell
Choices = require("choices.js")
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more