Reputation: 33
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
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
Reputation: 3854
You can do it like the following:
Append the select
element
var dropDown = d3.select("body").append("select")
.attr("name", "name-list");
Append options
to your select
element based on data
var options = dropDown.selectAll("option")
.data(data)
.enter()
.append("option");
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