I have an array var brands = ['Option1', 'Option2']
. I want to use D3 to output labelled radio buttons as follows:
<label>
<input type="radio" name="brand" value="Option1" checked="true"/> Option1
</label>
<label>
<input type="radio" name="brand" value="Option2" /> Option2
</label>
This is my D3, but it's not quite working:
var radios = d3.select('.panel.left').selectAll('input[name="brand"]').data(brands);
var labels = radios.enter()
.append("label")
.attr("for", function(d) { return d; })
.text(function(d) { return d; })
.append("input")
.attr("type", "radio")
.attr("name", "brand")
.attr("value", function(d) { return d; })
.attr('checked', function(d) { if (d === brands[0]) { return 'checked' }; });
d3.selectAll('input[name="brand"]').on('change', function() {
renderValues(this.value);
});
It's very close to working, but it outputs this:
<label>
Option1 <input type="radio" name="brand" value="Option1" checked="true" />
</label>
<label>
Option2 <input type="radio" name="brand" value="Option2" />
</label>
No matter what I do, I can't figure out how to put the text after the <input>
element. What should I be doing differently?
It would also be nice if I didn't have to re-select the input elements to add a listener, at the end.
Try adding this at the end of your script:
d3.selectAll("label")
.data(brands)
.append("text")
.text(function(d) { return d; });
And delete these lines:
.attr("for", function(d) { return d; })
.text(function(d) { return d; })
You don't need to re-select the input. After the .append("input") add the listener:
.append("input")
.on('change', function() {
renderValues(this.value);
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.