How To Set Default Value Appearing In Dropdown?
I have seen this answer which says to do this: .property('selected', function(d){ return d === defaultOptionName; }) But this isn't working for me. I'm trying to create a simple d
Solution 1:
When you do this...
dropdown.property("selected", "some default value");
... you have to ask yourself: what is dropdown
? It's a D3 selection, that's clear, but what selection?
Let's see:
var dropdown = d3.select("#dropDown")
.insert("select", "svg")
//etc...
Therefore, dropdown
refers to the <select>
, not to the options.
On top of that, you cannot set...
dropdown.property("selected", "some default value");
The selected
property is a boolean of a given option.
Solution: create a new selection for the <option>
s:
var options = dropdown.selectAll("option")
.data(cols)
.enter()
//etc...
And then:
options.property("selected", function(d){
return d === "some default value");
});
Where d === "some default value"
will return true
or false
for each datum.
Alternatively, you don't need to name the selection (but it's a good idea doing so), just add that method to the chain.
Here is a demo:
var cols = ["foo", "bar", "baz", "foobar", "foobaz"]
var dropdown = d3.select("body")
.append("select")
.attr('id', 'dropDownId');
var options = dropdown.selectAll("option")
.data(cols)
.enter()
.append("option")
.attr("value", function(d) {
return d;
})
.text(function(d) {
return d;
});
options.property("selected", function(d){return d === "foobar"});
<scriptsrc="https://d3js.org/d3.v5.min.js"></script>
Post a Comment for "How To Set Default Value Appearing In Dropdown?"