3

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.

2 Answers 2

6

This is how I create multiple buttons.

    d3.select("#some_id")
      .append("div")
      .attr("class","some_other_id")
      .each(function(d) {

    for (var i = 1; i < number_to_duplicate; i++) {
        d3.select("#some_other_id")
          .append("button")
          .attr("type","button")
          .attr("class","btn-btn")
          .attr("id",function(d) { return 'button '+i;})
          .append("div")
          .attr("class","label")
          .text(function(d) { return 'button '+i;})

I create a div and an .each(function). In the function the for loop creates the buttons. This gives me as many buttons as I want - number_to_duplicate - each with individual id. Of course I can modify this an make more buttons, with equal or different attributes, appending those to a different yet_another_id element.

The labels could be done outside the loop elsewhere if desired. This is my poor man's 'button factory'. Please comment with critique, positive or negative - for me to learn from.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.