user2829582
user2829582

Reputation: 245

How to add two buttons to a div with D3.js?

I'm attempting to add two buttons to a div, one beneath the other. The first button accepts a number and the second will be used to toggle lines on and off.

Only the second button I append is created. How do I create two buttons in the same div?

Here is a JSFiddle.

<!DOCTYPE html>
<meta charset="utf-8">
<html>
<script src="d3.js"></script>
<body>
<div id=options>
<script>

(function(){
  var form = d3.select("#options")
      .append("form")
      .html("Enter a number:")

  form.append("input")
      .attr("type", "text")
      .attr("name", "num")

  form.append("input")
      .attr("type", "button")
      .attr("value", "Add")
      .attr("onclick", "printNum(num.value)")

  form.html("Show/hide lines:")    
      .append("input")
      .attr("type", "button")
      .attr("name", "toggle")
      .attr("value", "Toggle")
      .attr("onclick", "togglePressed()");
})();

function printNum(num){
  alert("You entered " + num + "!");
}

function togglePressed(){
  alert("You pressed the toggle button!");
}
</script>
</div>
</body>
</html>

Upvotes: 3

Views: 7325

Answers (1)

wesww
wesww

Reputation: 2873

The problem is that you're setting the html of the form after trying to append things to the form. So in other words, the append functions work, and then you destroy everything and swap it out for what is in your .html function.

either move this block to before the append calls:

form.html("Show/hide lines:")    
  .append("input")
  .attr("type", "button")
  .attr("name", "toggle")
  .attr("value", "Toggle")
  .attr("onclick", "togglePressed()"); 

or alternately, don't use the .html function.

reference: "setting the inner HTML content will replace any existing child elements" https://github.com/mbostock/d3/wiki/Selections#html

updated jsfiddle: http://jsfiddle.net/kueuLLr4/

Upvotes: 6

Related Questions