Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update d3 table?

I have some problem to update my d3.js table when mousemoving. Here is a simplified example in jsfiddle.

Here is the main code:

 function mousemove() {

  var newdata = [{Variable: "x", Value: 1}, {Variable: "y", Value: 1}]

  table.selectAll("tbody.tr")
    .data(newdata)
    .enter()
    .append("tr")
    .selectAll("td")
    .data(function(row) {
      return columns.map(function(column) {
        return {column: column, value: row[column]};
      });
    })
    .enter()
    .append("td")
    .text(function(d) { return d.value; });
};

namely, how can I only update the values in the table instead of drawing a new table again and again?

Thank you!

like image 780
leonsPAPA Avatar asked Mar 15 '23 15:03

leonsPAPA


1 Answers

Use your previously defined selections(in jsfiddle example)

var table = d3.select("body").append("table");
var tbody = table.append("tbody");

Using this selection, you can update the existing table. In your mouseover() function, you have used enter() as an attempt to update your table. But since enter() sees that required number of placeholders (2 placeholders for 2 rows) are already present, it will not do anything. You can update by removing enter() and append statements and doing something like:

tbody.selectAll("tr")
  .data(newdata)
  .selectAll("td")
  .data(function(row) {
    return columns.map(function(column) {
      return {
        column: column,
        value: row[column]
      };
    });
  })
  .text(function(d) {return d.value;});

Ideally you should follow the enter(), update() and exit() sequence for such d3 updates, but for this situation just the above changes will suffice.

like image 157
Rajeev Atmakuri Avatar answered Mar 20 '23 06:03

Rajeev Atmakuri