How do I set the option selected on load when creating multiple dropdowns?
When the page finishes loading, the first dropdown should have 'Horse' selected, the second dropdown should have 'Cow' selected, and the third dropdown should have 'Fox' selected.
let widgetContainer = d3.select('#dropdowns')
let animalNames = ["Horse", "Dog", "Cow", "Fox", "Cat", "Pig", "Aardvark", "Baboon", "Elephant"]
let selectedNames = ["Horse", "Cow", "Fox"]
let dropdowns = widgetContainer
.selectAll(".widget-select")
.data(selectedNames)
.join("select")
.attr("id", (d, idx) => `select-${idx}`)
.attr("class", "animal-select")
.on("change", (animalName, idx, selectElements) => {
let selectedValues = selectElements.map((elem) => elem.value);
// function that sets state for graph and renders
onAnimalSelect(selectedValues);
});
let options = dropdowns
.selectAll("option")
.data(animalNames)
.join("option")
.property("selected", (opt) => {
// how to find the parent node to set selected?
})
.attr("value", (opt) => opt)
.text((opt) => opt);
Here's a JSFiddle: https://jsfiddle.net/denisemauldin/x0znphky/3/