Reputation: 2617
First consider how easy it is to populate a drop down menu with D3:
var options = [
"option 1",
"option 2",
"option 3",
"option 4"
];
d3.select("#my_select")
.selectAll("option")
.data(options)
.enter().append("option")
.attr("value", function(d) { return d; })
.text(function(d) { return d; });
However, I'm not quite sure how I can append an HTML user input that is not already preexisting, and it also doesn't need to be 'populated' with the data()
call. In my case I simply want to append a number input for the user. I tried this (and many similar variants):
graphGroup.append('input')
.attr('type','number');
That didn't work. So I then looked at the pure javascript solution, which looks something like this:
var newdiv = document.createElement('div');
newdiv.innerHTML = "New Entry " + " <br><input type='number' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
But, I would hope that d3 has a slightly more elegant solution. The reason being, my input appending needs will surely evolve as I progress with my project. During my research, I have not found a d3 example of this, so I'm really keen on figuring out the d3 approach.
Upvotes: 1
Views: 1540
Reputation: 3854
You can do it directly with d3 like this. I have added both a dropdown and a numberic html input.
var options = [
"option 1",
"option 2",
"option 3",
"option 4"
];
var select = d3.select("body")
.append("div")
.append("select");
var input = d3.select("body")
.append("div")
.append("input")
.attr("type", "number");
select
.on("change", function(d) {
var value = d3.select(this).property("value");
alert(value);
});
select.selectAll("option")
.data(options)
.enter()
.append("option")
.attr("value", function(d) {
return d;
})
.text(function(d) {
return d;
});
Check Fiddle here - https://jsfiddle.net/2k5j5xag/
Upvotes: 1