简体   繁体   中英

D3 v3 appending checkbox?

Am working with collapsible tree top to bottom orientatin. Here i stuck with some problem. To implement the tree am using d3.v3.js. How can i append check box into the tree for each node.

    // Create the link lines.
    svg.selectAll(".link")
        .data(links)
      .enter().append("path")
        .attr("class", "link")
        .attr("d", d3.svg.diagonal().projection(function(d) { return [o.x(d)+15, o.y(d)]; }));

        svg.selectAll("input")
        .data(nodes)
        .enter().append("foreignObject")
        .attr('x' , o.x)
        .attr('y',  o.y)
        .attr('width', 50)
        .attr('height', 20)
        .append("xhtml:body")
        .html("<form><input type=checkbox id=check></input></form>")
     .on("click", function(d, i){
            console.log(svg.select("#check").node().checked) 
            }) ;

    svg.selectAll("image")
        .data(nodes)
     .enter().append("image")
        .attr('x' , o.x)
        .attr('y',  o.y)
        .attr('width', 30)
        .attr('height', 20)
        .attr("xlink:href", "check.png")
  }); 
});

Checkbox in appending in to svg but not been visible in browser. Anybody please help me to solve this issue

You need to be creating a holder for the foreignObjects (ie checkbox's) and not the inputs in this line:

svg.selectAll("input")

which should be

svg.selectAll("foreignObject")

you then need to drive the number of checkbox's with the data as in, data(data) and bind it with the enter() , as you've done. If you want multiple elements to appear you need to use dynamic variable for the x and y. In a simple example that would be .attr('x', function (d,i) { return dx; }) . So putting it all together in a fiddle you get this .

Your checkbox does not appear because you cannot append arbitrary html elements to svg. You should use either < g > or floating elements:

#canvas {
  position: relative;
}

Then append checkbox element using:

d3.select("#canvas")
  .append("input")
  .attr("type", "checkbox")
  .style("position", "absolute")
  .style("top", "320")
  .style("left", "150")

This answer is more usefull those are using Bootstrap .To append checkbox in bootstrap we need to specify label and span expectly while appending foreign object. Otherwise it not be visible in browser

 svg.selectAll("foreignObject")
   .data(nodes).enter()
   .append("foreignObject")
   .attr('x', o.x)
   .attr('y',  o.y)
   .attr('width', 30)
   .attr('height', 20)
   .append("xhtml:tree")
   .html("<label class='inline'><input type='checkbox'><span class='lbl'> </span>               </label>");

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM