I am trying to display the values of an array, but for some reason it shows only NaN… can somebody help with the job? thanks in advance.
<td> <div class="values"> {{ value1 }} </div> </td> <td> <div class="values"> {{ value2 }} </div> </td> <td> <div class="values"> {{ value3 }} </div> </td>
var data = d3.selectAll('.values').nodes(); console.log(data); var pie = d3.pie() //we create this variable, for the values to be readeable in the console .value(function(d) {return d.value; })(data); console.log(pie);
{{ Value1 }}, {{ Value2 }} and {{ Value 3 }} are being deployed correctly, this is a picture from the html:
Advertisement
Answer
Your recent question used text input elements to create a pie chart. These elements have a property called value
. A div does not.
When you use this, where d
refers to an element:
.value(function(d) {return d.value; })(data);
Input elements will return a value, and the divs will return undefined. Hence your NaN error:
console.log("div.value: ",d3.select("div").node().value); console.log("input.value: ",d3.select("input").node().value); console.log("input value an empty string: that's the content of the field");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script> <div>text</div> <input></input>
But if your div elements only contain the relevant text, then we can use something like element.innerHtml
to get the data.
console.log(d3.select("div").node().innerHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script> <div>50</div>
If you swap:
var pie = d3.pie() .value(function(d) {return d.value; })(data);
With:
var pie = d3.pie() .value(function(d) {return d.innerHTML; })(data);
You should have a working solution.
Note, in both cases (input or div) the input is a string, this can cause issues depending on how you use the data, it’s often a good idea to coerce the data to a number, which you can do with a unary +
:
var pie = d3.pie() .value(function(d) {return +d.innerHTML; })(data);