Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default selection of a dropdown menu with D3

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.

like image 275
Null-Username Avatar asked Nov 12 '14 23:11

Null-Username


1 Answers

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; })
like image 126
Null-Username Avatar answered Nov 16 '22 09:11

Null-Username