D3 create buttons from an array of string containing names

guillaume guerin picture guillaume guerin · Mar 6, 2013 · Viewed 7.9k times · Source

I'd like to create several buttons in d3. in order to have a clearer code I'd like to add their names in an array.

I have the following code, but it doesn't work :

var buttonNames = ["button 1", "button 2", "button 3", "button 4"]

d3.select("body").selectAll("input").data(buttonNames).enter().append("input").attr("type","button").attr("class","button").attr("value", function d(){return d;} )

Thanks in advance for your reply.

Answer

Lars Kotthoff picture Lars Kotthoff · Mar 6, 2013

There's a typo in your function definition.

.attr("value", function d(){return d;} )

should be

.attr("value", function (d){return d;} )

Note that d is an argument to the function and has to be inside the parentheses.