Home > database >  Dropdown select with default value
Dropdown select with default value

Time:06-22

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/

CodePudding user response:

Using the second and third parameters combined gives us the DOM element (n[i] in this example), and from that we can go up to its parent using parentNode. Therefore, it can be:

.property("selected", (opt, i, n) => d3.select(n[i].parentNode).datum() === opt)

Here is your code with that change:

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, i, n) => d3.select(n[i].parentNode).datum() === opt)
  .attr("value", (opt) => opt)
  .text((opt) => opt);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.4.0/d3.min.js"></script>
<p>
  Here are some dropdowns. How do we set the default value on load?
</p>
<div id="dropdowns">
</div>

  • Related