Skip to content

Instantly share code, notes, and snippets.

@jfreels
Last active June 1, 2016 18:35
Show Gist options
  • Save jfreels/6811178 to your computer and use it in GitHub Desktop.
Save jfreels/6811178 to your computer and use it in GitHub Desktop.
d3js: Create select box with optgroup and create a paragraph showing the value of the selection.

d3js: Create select box with optgroup and create a paragraph showing the value of the selection.

<!DOCTYPE html>
<meta charset='utf-8'>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<script type='text/javascript' src='script.js'></script>
</body>
</html>
var body = d3.select('body')
var optGroupJSON = [
{ "key" : "Group 1", "value": ["Option 1","Option 2","Option 3"] },
{ "key" : "Group 2", "value": ["Option 4","Option 5","Option 6"] }
]
body.append('select')
.on('change',function () {
d3.select('body')
.selectAll('p')
.remove()
d3.select('body')
.selectAll('p')
.data([d3.select('select').property('value')])
.enter()
.append('p')
.text(function (d) { return d })
})
.selectAll('optgroup')
.data(optGroupJSON)
.enter()
.append('optgroup')
.attr('label',function (d) { return d.key})
.selectAll('option')
.data(function (d) { return d.value })
.enter()
.append('option')
.attr('value',function (d) { return d })
.text(function (d) { return d })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment