Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to add a drop down menu to my d3 visualization. The problem is that the eventlistener does not get invoked on selecting any of the options. Also, how can I access the value of the option selected? Following is a snippet of my code..

d3.text("uniqueTeams.php",function(json){
    var dd=JSON.parse(json);
    var b= d3.select("#s4").select("#shru");
    var u=b.append("select");
    var t=u.selectAll("option").data(dd).enter().append("option")
        .attr("value",function(d){return d.teamShotID;})
        .text(function(d){return d3.select(this).node().__data__.teamShotID;});
    t.on("change",change);
});
function change(value)
{
    console.log("team",value);
}
change();????

Thankx

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
148 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to add the .on("change") to the select element, not the option elements.

var select  = d3.select("#shru").append("select").on("change", change),
    options = select.selectAll('option').data(dd); // Data join

// Enter selection
options.enter().append("option").text(function(d) { return d.teamShotID; });

The currently selected option index is kept in a property called selectedIndex on the select element. Selections are arrays, so elements can be accessed directly (e.g., selection[0][0]). Each option element will have data bound to it, stored in a property called __data__:

function change() {
    var selectedIndex = select.property('selectedIndex'),
        data          = options[0][selectedIndex].__data__;
}

Edit: For readability and hopefully to help you understand the code above, I'd like to also include this alternative syntax:

function change() {
    var si   = select.property('selectedIndex'),
        s    = options.filter(function (d, i) { return i === si }),
        data = s.datum();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...