Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return data based on dropdown menu?

Tags:

d3.js

I am building a basic scatter plot where I'd like to highlight specific points in my plot based on a dropdown selection. My code looks like this:

fill_arr = fill.range();
labels = ["A", "B", "C", "D"];
options = [0, 1, 2, 3];

// Build the dropdown menu
d3.select("#drop")
    .append("select")
    .selectAll("option")
    .data(options)
    .enter()
    .append("option")
    // Provide available text for the dropdown options
    .text(function(d) {return labels[d];})

d3.select('select')
    .on("change", function() {
    // HOW CAN I GET THE OPTION THAT THE USER HAS SELECTED FROM THE DROPDOWN?
    key = 0 // <- I can do this manually, but I want to get the label the user has selected
    d3.selectAll('circle')
        .transition()
        .duration(300)
        .ease("quad")
        .attr( 'r', 5)
        .attr('cx', function(d) {return d.x;})
        .attr('cy', function(d) {return d.y;})
        // if a data point is selected highlight other 
        // data points of the same color
        .style('fill', function(d, i) { 
            if (d.label == key) 
            {return fill_arr[key]}
            else {return "#ccc"}
        ;})
    });

My issue is that I don't know how to determine what the user has selected from the dropdown. How can I determine which option, ["A", "B", "C", "D"] the user has selected?

like image 534
user1728853 Avatar asked Oct 21 '22 09:10

user1728853


1 Answers

Access it using this.selectedIndex:

d3.select('select')
    .on("change", function() {

    key = this.selectedIndex;

    d3.selectAll('circle')
        .transition()
        .duration(300)
        .ease("quad")
        .attr( 'r', 5)
        .attr('cx', function(d) {return d.x;})
        .attr('cy', function(d) {return d.y;})
        // if a data point is selected highlight other 
        // data points of the same color
        .style('fill', function(d, i) { 
            if (d.label == key) 
            {return fill_arr[key]}
            else {return "#ccc"}
        ;})
});
like image 195
mccannf Avatar answered Nov 03 '22 19:11

mccannf