I created a dropdown menu of some months as options, but wanted to predesignate one option as the default value. However, the default selection seemed to stubbornly remain the first option in the list.
I tried the below code, which made a lot of sense to me because for any other attribute, setting up a simple comparison is sufficient to alter that attribute's 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 right syntax, but when I tried to search the internet and stackoverflow, but couldn't figure out what I was missing.
I found that instead of using .attr
, I needed to use .property
in order to access the default selection option. A simple substitution was all that was required, so your code snippet would look something like:
.property("selected", function(d){ return d === defaultOptionName; })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With