Changing Node Text (and preserving changes)
http://stackoverflow.com/questions/20534883/d3-update-data-behind-the-visualization#22369507
by Nivaldo
HTML
<H3>Rename tree and get underlying data to push to server.</h3>
<script>
var money;
</script>
JavaScript
var data = {
"name": "Blog",
"children": [
{
"name": 'Sylvia',
"children": [
{"name": "Tom"},
{"name": "Jeft"},
{"name": "Buffy"}
]
},
{
"name": "David",
"children": [
{"name": "Jeft"},
{
"name": "Buffy",
"children": [
{'name': "test"}
]
}
]
}
]
};
var canvas = d3.select("body").append('svg')
.attr("width",500)
.attr("height",500)
.append('g')
.attr("transform", "translate(50,50)");
var draw = (function() {
var tree = d3.layout.tree()
.size([400,300]);
// Let D3 convert JSON into d3.node array
var nodes = tree.nodes(data);
var linkedNodes = tree.links(nodes); //Creates a start and end
// Add all the nodes
var node = canvas.selectAll('.node')
.data(nodes);
node
.enter()
.append('g')
.attr('class','node')
.attr('transform', function(d){ return "translate(" + d.y + "," + d.x + ")"; });
// Add circle
node.append("circle")
.attr('r', 5)
.attr("fill", 'green');
// Add text
node.append("text")
.text(function(d){ return d.name; })
.on('click', function(d){
var result = prompt('Change the name of the node',d.name);
if(result) {
d.name = result;
var node1 = canvas.selectAll('.node').data(nodes);
node1.select('text')
.text(function(d){ return d.name; });
console.log(filter(node1.data()[0]));
// This will give the data as put into the function a the top. Now you only need to loop through the array to remove the additional attributes d3 has added.
money = node1.data()[0];
}
});
// Filter funciton
function filter(data) {
for(var i in data){
if(["depth","x","x0","y","y0","parent","size"].indexOf(i) != -1){
delete data[i];
} else if (i === "children") {
for (var j in data.children) {
data.children[j] =...