Reputation: 199
I am trying to generate a table which is being embedded into SVG with a structure like this:
<table>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
out of a dataset like this:
var a = ["a", 1, "b", 2, "c", 3]
so that the count of tags is dynamic depending on the number of key-value pairs, so in this case 2. Inside of it would be a static number of two td's each with the key and value respectively.
So far I have tried something like this:
var tr = ele.append("svg:foreignObject")
.attr("x", 5)
.attr("y", 30)
.attr("width", 60)
.attr("height", 120)
.append("xhtml:body")
.attr("xmlns", "http://www.w3.org/1999/xhtml")
.selectAll("tr")
.data(d3.keys(a))
.enter().append("tr");
tr.selectAll("td").data(a).enter()
.append("td")
.text(function (d) { return d; } );
which results in something like this:
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
So, a correct number of rows, but an incorrect number of tds.
Edit: Performing a
tr.append("td").text("test");
tr.append("td").text("test2");
results in a correct structure, although when I try to iterate through the dataset using the .data() function with two separate appends, it of course adds two duplicate tds.
Edit 2: I have ended up solving my problem by generating the HTML for the table outside of d3.js chain and just appending it as .html(). Is there any neater way of doing it?
Upvotes: 2
Views: 791
Reputation: 5342
You can structure your data like this: [["a",1],["b",2],["c",3]]
.
Then you can do:
var tr = table.selectAll("tr").data(data);
tr.enter().append("tr");
tr.each(function(d) {
var td = d3.select(this).selectAll("td").data(d);
td.enter().append("td");
})
Something like that.
Haven't compiled, but it should give you an idea.
Upvotes: 1