I'm trying to join existing input text (selected by d3.selectAll()
) that have unique id's corresponding to keys in the data joined with D3.
I would like D3 to associate the ids of the input elements to the keys of the data, but it doesn't.
Association is done in the order in witch they appear in the DOM and in the array respectively.
Is there a way to do this ?
Remember that the key function will be invoked on each element of your data array (i.e. dt), as well as on each element in your selection (i.e. d3.selectAll(".input")). In both cases, the key function needs to return a valid value and those output values will used to make the association.
To achieve your goal you can do something like the following example. See fiddle for live version: http://jsfiddle.net/2Fkjq/
If your document contains the following:
<div id="c"></div>
<div id="a"></div>
<div id="b"></div>
then executing this:
var data = [
{ key: "a", val: "aaa" },
{ key: "b", val: "bbb" },
{ key: "c", val: "ccc" }
];
d3.selectAll("div")
.data(data, function(d) { return (d && d.key) || d3.select(this).attr("id"); })
.text(function(d) { return d.val; });
will result in this document:
<div id="c">ccc</div>
<div id="a">aaa</div>
<div id="b">bbb</div>
You see that the key function consists of two parts. The first part is designed for the data array:
(d && d.key)
That part will return undefined
for the elements in the d3 selection. The second part targets those elements:
d3.select(this).attr("id")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With