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

d3.js, forms, html, html-select, javascript

Solution

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/

Problem

Is there 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/

Original source