Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use D3 (or just javascript) to set a form option as being "selected"

I am trying to learn D3. Is there an elegant a way to search through all the options in a select form element and specify an option with a matching value as being "selected"?

var xStat = "G";

var statOptions = {
    "Points": "PTS",
    "Goals": "G",
    "Assists": "A",
    "Penalty Minutes": "PIM"
};

// create the select element
var selectUI = d3.select("#horse").append("form").append("select");

// create the options
selectUI.selectAll("option").data(d3.keys(statOptions)).enter().append("option").text(function(d) {
    return d;
});

// add values to the options
selectUI.selectAll("option").data(d3.values(statOptions)).attr("value", function(d) {
    return d;
});


// create a func to check if the value of an option equals the xStat var
// if yes, set the attribute "selected" to "selected"
var checkOption = function(e, i, a) {
    if (e[i]["value"] === xStat) {
        return e[i].attr("selected", "selected");
    }
};

// selectUI.selectAll("option").forEach(checkOption);
selectUI.selectAll("option").call(checkOption);​

I've included my non-working attempt at doing this here: http://jsfiddle.net/sspboyd/LzrAC/2/

Thanks.

like image 366
sspboyd Avatar asked Oct 27 '12 06:10

sspboyd


2 Answers

After checking some values with breakpoints I've figured out how to make this work. The problem was with the last few lines of code. The revised (and working) code is this:

var checkOption = function (e) {
    if(e === xStat){
        return d3.select(this).attr("selected", "selected");
    }
};

selectUI.selectAll("option").each(checkOption);

I was getting two things wrong. First, I was using .call() instead of .each() (each/call API reference).

Second, I had assumed that selecting the option elements in selectUI would give me an array of the option html elements which I could test by looking for 'value' of each array entry. Looking at the console (thank you chrome) I eventually figured out that I was actually getting the values of each option entry. I have no idea why this is the case. I'd love to know if someone can explain. Also, I ended up referencing the option element via 'this', no idea why that works either.

Hope this helps someone else. I've updated the jsfiddle example to the now working code. http://jsfiddle.net/sspboyd/LzrAC/3/

Stephen

like image 42
sspboyd Avatar answered Oct 26 '22 23:10

sspboyd


This appears to work:

  selectUI.property( "value", xStat );

Newbie myself and was fumbling on the same issue. If this is not the right way, I'd be interested to know what is.

http://jsfiddle.net/saipuck/LzrAC/9/

like image 81
sai Avatar answered Oct 27 '22 00:10

sai