user3246812 user3246812 - 3 years ago 99
HTML Question

Populate Dropdown list with CSV file - d3

I want to populate simple drop down list in html ,
with values that exist in csv file.
I try something like that , but it doesn't work.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>

</body>
<script src="http://d3js.org/d3.v3.js"></script>
<script>
d3.csv("valuesforDD.csv", function(error, data) {

var select = d3.select("body")
.append("div")
.append("select")


select.selectAll("option")
.data(data)
.enter().append("option")
.attr("value", function (d) { return d; })
.text(function (d) { return d; });

}

</script>

</html>


What should I change?

thank you

Answer Source
  1. d3.csv uses the first line of the CSV file as the column names. You should make sure your CSV file looks something like the following:

    value,label
    1,"Item 1"
    2,"Item 2"
    3,"Item 3"
    
  2. You must use a field name when accessing the data in the attr and text functions. Using the above CSV file, you would use d.value and d.label.

Here is an updated version of your code that you should be able to use and adapt as needed:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
  <script src="http://d3js.org/d3.v3.js"></script>
  <script>
  d3.csv("valuesforDD.csv", function(error, data) {
    var select = d3.select("body")
      .append("div")
      .append("select")

    select
      .on("change", function(d) {
        var value = d3.select(this).property("value");
        alert(value);
      });

    select.selectAll("option")
      .data(data)
      .enter()
        .append("option")
        .attr("value", function (d) { return d.value; })
        .text(function (d) { return d.label; });
  });
  </script>
</body>
</html>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download