简体   繁体   中英

How to set default option d3.js

I have a drop down list in my plot to select the point user wants to display. A is green. B is yellow and it is my default option. When the plot is first loaded, I want only yellow points showed in the plot. But here it shows all the points in the data. Can anyone tell me how do I fix it?

var defaultOption = ["B"];
var dropDown = d3.select("#filter").append("select")
                .attr("type", "AB")
                .attr("class","list");

var options = dropDown.selectAll("option")
       .data(d3.map(data, function(d){return d.type;}).keys())
       .enter()
       .append("option") 
      .property("selected", function(d){
    return d == defaultOption;})  
     .text(function (d) { return d; })
      .attr("value", function (d) { return d; });

    dropDown.on("change", function() {
  var selected = this.value;
  displayOthers = this.checked ? "inline" : "none";
  display = this.checked ? "none" : "inline";

  svg.selectAll(".circles")
      .filter(function(d) {return selected != d.type;})
      .attr("display", displayOthers);

  svg.selectAll(".circles")
      .filter(function(d) {return selected == d.type;})

You can do something like this:

Move the part which filters circle in a function like below showCircles

showCircles(dropDown.node());//this will filter initially
dropDown.on("change", function() {
  showCircles(this);//this will filter the circles on change of select
});
//function to show circles as per the select box
function showCircles(me){
  console.log(me);
  var selected = me.value;
  displayOthers = me.checked ? "inline" : "none";
  display = me.checked ? "none" : "inline";

  svg.selectAll(".circles")
    .filter(function(d) {
      return selected != d.type;
    })
    .attr("display", displayOthers);

  svg.selectAll(".circles")
    .filter(function(d) {
      return selected == d.type;
    })
    .attr("display", display);
}

working code here

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM