Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  115] [ 4]  / answers: 1 / hits: 29124  / 11 Years ago, thu, february 13, 2014, 12:00:00

Error in code below. There is no issue with the data of the remaining fields.



<!DOCTYPE html>
<html>
<head>
<title>Data Entry</title>
<meta charset='utf-8'/>
<meta name=keywords content=D3/>
<script type=text/javascript src=d3/d3.v3.js></script>
<style type=text/css>
.table {border: 2px; text-align: center;}
.th {font-size: 12px; font-weight: bold; color: blue;}
.td {font-size: 12px;}
</style>
</head>
<body>
<script type=text/javascript>
var dataset;
d3.text('data.txt', function(d){dataset = d3.csv.parse(d, function(d){return {id: +d.id, name: d.name};});});
d3.select('body').append('table').attr('class','table').selectAll('tr').data(dataset).enter().append('tr');
</script>
</body>
</html>


Screenshot below:Error


More From » d3.js

 Answers
34

There are two things you need to consider, the first is that you've put the reference to dataset outside of your call back function. So while you've created the dataset variable as a global so that it can be accessed outside of the d3.text block it hasn't had time to be populated when the table is generated. So if you move your table generation code into the d3.text block you'll address this issue. You can also queue your data requests using queue.js.



The other thing was that you were trying to bind a single element array of objects, where you need an array of objects as d3 iterates over the array to create, in this case, table rows. The information in the objects is then used to populate your table.



Both of these issues are addressed in the following code, however, note that I haven't populated the tables cells with any thing, just created the rows. To do that I'd suggest reading d3noobs post
and the referenced stackoverflow answer by Shawn Allen.



var dataset =[];
d3.text('data.txt', function(d) {
d3.csv.parse(d, function(d) {
var el = {
id: +d.id,
name: d.name
};
dataset.push(el)
});
var table = d3.select('body')
.append('table')
.attr('class', 'table');

table.selectAll('tr')
.data(dataset).enter()
.append('tr')
.attr(class, rows);

});


One final thing is that you could just use d3.csv instead of d3.text and d3.csv.parse.


[#72534] Wednesday, February 12, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
makenatiffanic

Total Points: 412
Total Questions: 106
Total Answers: 90

Location: Marshall Islands
Member since Tue, Sep 21, 2021
3 Years ago
;