Skip to content

Instantly share code, notes, and snippets.

@jfreels
Last active December 26, 2015 04:09
Show Gist options
  • Save jfreels/7091040 to your computer and use it in GitHub Desktop.
Save jfreels/7091040 to your computer and use it in GitHub Desktop.
d3js: D.R.Y. update/enter/exit paragraph with Select input

d3js: D.R.Y. update/enter/exit paragraph with Select input

<!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 data = [1,2,3]
var selectBody = d3.select('body')
var selectInput = selectBody.append('select')
.on('change',addP)
var selectOptions = selectInput.selectAll('option')
.data(data)
var returnD = function (d) { return d;}
selectOptions.enter()
.append('option')
.attr('value',returnD)
.text(returnD)
addP();
function selectValue() {
return d3.select('select').property('value')
}
function addP() {
var ps = selectBody.selectAll('p')
.data([selectValue()])
ps.text(returnD) // update
ps.enter() // enter
.append('p')
.text(returnD)
ps.exit().remove() // exit
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment