Populate Dropdown list with CSV file - d3

14,205
  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>
Share:
14,205

Related videos on Youtube

user3246812
Author by

user3246812

Updated on September 15, 2022

Comments

  • user3246812
    user3246812 over 1 year

    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

  • Rohit Poudel
    Rohit Poudel over 6 years
    Please add description to answer. @Harshal
  • Harshal
    Harshal over 6 years
    check the code now ... its so simple to understand ... html code at top and below the js code thats it...