soniccool
soniccool

Reputation: 6058

Convert on screen csv text to table

I have a div class that contains the raw text for a csv below:

<div class="weh">
    Jones, Smith, and Company
    test, meow
</div>

Is there a way i can load this div and display it as a table rather than just the raw text on the html render?

I found this code that works below but it only works for loading an actual file. How can i modify it to load whats in my div class weh and load a csv style table below it.

<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style>
    table {
        border-collapse: collapse;
        border: 2px black solid;
        font: 12px sans-serif;
    }

    td {
        border: 1px black solid;
        padding: 5px;
    }
</style>
<script type="text/javascript"charset="utf-8">

      d3.text("excel.csv", function(data) {
          var parsedCSV = d3.csv.parseRows(data);

          var container = d3.select(".module-content")
              .append("table")

              .selectAll("tr")
                  .data(parsedCSV).enter()
                  .append("tr")

              .selectAll("td")
                  .data(function(d) { return d; }).enter()
                  .append("td")
                  .text(function(d) { return d; });
      });
  </script>

Upvotes: 0

Views: 26

Answers (1)

rioV8
rioV8

Reputation: 28673

Just extract the text from the DOM

var csvText = d3.select("#weh").text();

var csvText = d3.select("#weh").text();
console.log(csvText);
var parsedCSV = d3.csv.parseRows(csvText);
console.log(parsedCSV);
var container = d3.select("body")
    .append("table")

    .selectAll("tr")
      .data(parsedCSV).enter()
      .append("tr")

    .selectAll("td")
      .data(function(d) { return d; }).enter()
      .append("td")
        .text(function(d) { return d; });
table, td { border: 1px solid #000000; }
td { padding: 0.5em; }
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>

<div id="weh" style="display:none;">Jones,Smith,Company
test,meow,foofoo
</div>

Upvotes: 2

Related Questions