OK I’ve been trying to append some checkbox’s to a div dynamically based on the number of columns in a dataset. So I thought d3 would be the way to go, simply append the input with the appropriate attributes and some text for the label determined from the data. I’ve tried the following code;
d3.select("body").selectAll("input")
.data([11, 22, 33, 44])
.enter().append("input")
.attr("checked", true)
.attr("type", "checkbox")
.attr("id", function(d,i) { return i; })
.attr("onClick", "change(this)")
.attr("for", function(d,i) { return i; })
.text(function(d) { return d; });
Which results in 4 checkboxs on the page but no labels.
What’s really strange is that when I inspect the elements the html generated seems to be what I’m after as shown below.
<input checked="true" type="checkbox" id="0" onclick="change(this)" for="0">11</input>
<input checked="true" type="checkbox" id="1" onclick="change(this)" for="1">22</input>
<input checked="true" type="checkbox" id="2" onclick="change(this)" for="2">33</input>
<input checked="true" type="checkbox" id="3" onclick="change(this)" for="3">44</input>
When I use this on a page I get exactly what I’m after.
I’m sure I’m missing something extremely simple, but for the life of me I can’t see what it is. Any help gratefully accepted!
Your main problem is that you can’t put text in between
<input>tags like that. They are self-closing like<input />. You should use the<label>element for that text.Other problem is that ID’s must begin with a letter (at least, before HTML5), so
id="1"won’t work, butid=a1"will.That said, this code solves those two problems