Default setting for dropdown menu with D3

I created a few months dropdown menu as parameters, but wanted to precede one option as the default value. However, the default choice seemed to stubbornly remain the first option on the list.

I tried the code below, which made a lot of sense to me, because for any other attribute, a simple comparison is enough to change this attribute value.

var defaultOptionName; // desired default dropdown name d3.select("#dropdown").append("select") .on("change", someFunction) .selectAll("option").data(dataset) .enter().append("option") .attr("value", function(d){return d;}) .attr("selected", function(d){ return d === defaultOptionName; }) .text(function(d){ return d; }); 

I knew that my problem was just a matter of the correct syntax, but when I tried to search the Internet and stackoverflow, but could not understand what I was missing.

+5
source share
1 answer

I found that instead of using .attr I needed to use .property to access the default selection option. A simple replacement is all that was required, so your piece of code will look something like this:

  .property("selected", function(d){ return d === defaultOptionName; }) 
+9
source

Source: https://habr.com/ru/post/1206755/


All Articles