angel
angel

Reputation: 33

how to append option into select combo box in d3

I want to add the option into select combo box for example I have data like

[{ "NAME": "JONE", "ID": {"id1":123,"id2":124}}, { "NAME": "ANGEL", "ID": {"id1":125,"id2":127}}]` 

I want to append into options the "Name", I have done this so far:

dataset=d3.json("namees.json", function(data) {
    select = d3.select('body')
    .append('select')
    .attr('class','style');
    options = select
    .selectAll('option')


    .append('option')
            .text(data.forEach(function (d) {return d.Name}))



});

But it doesn't show the values in select option

Upvotes: 3

Views: 7864

Answers (2)

Bimal Prabha
Bimal Prabha

Reputation: 11

Data

let data = [{
  NAME: "JONE",
   ID: {
   "id1": 123,
   "id2": 124
  }
  }, {
  NAME: "ANGEL",
    ID: {
     "id1": 125,
"id2": 127
      }
}];

Javascript

    let selector = d3.select("#selDataset");
    let sampleNames = data.map(ele =>ele.NAME);
            
    sampleNames.forEach((sample) => {
        selector
            .append("option")
            .text(sample)
            .property("value", sample);
    });

Html Code

                <div class="well">
                <h5>Dropdown Menu:</h5>
                <select id="selDataset" onchange="optionChanged(this.value)"></select>
                </div>

Explanation Js object items shouldnt be string. I f you try with above script you should be able to get dropdown menu with name.

Upvotes: 1

sparta93
sparta93

Reputation: 3854

You can do it like the following:

  1. Append the select element

     var dropDown = d3.select("body").append("select")
        .attr("name", "name-list");
    
  2. Append options to your select element based on data

    var options = dropDown.selectAll("option")
     .data(data)
     .enter()
     .append("option");
    
  3. Set the text and value for your options

    options.text(function(d) {
    return d.NAME;
     })
       .attr("value", function(d) {
    return d.NAME;
    });
    

JSFiddle - https://jsfiddle.net/x4a8ejk6/

Upvotes: 9

Related Questions