Skip to content

Instantly share code, notes, and snippets.

@johnnygizmo
Last active May 24, 2016 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnnygizmo/3d593d3bf631e102a2dbee64f62d9de4 to your computer and use it in GitHub Desktop.
Save johnnygizmo/3d593d3bf631e102a2dbee64f62d9de4 to your computer and use it in GitHub Desktop.
Interacting with D3 and a Checkbox
license: gpl-3.0
height: 275

Just a quick example to show one way to use a checkbox or other form element to trigger a D3 data update. There are probably better ways, but this seems to work.

All row creation is pushed into the update() function and it is called once at the beginning. Then upon changing the checkbox, it is re-run and the checkbox state determines how the data is filtered before being rebound to the rows.

<html>
<head>
<script src="https://d3js.org/d3.v4.0.0-alpha.40.min.js"></script>
</head>
<body>
<input type="checkbox" id="myCheckbox"> Only Even
<div id="content"></div>
<script>
data = [2,4,5,7,12,123,352,1000];
table = d3.select("#content")
.append("table")
.property("border","1px");
d3.select("#myCheckbox").on("change",update);
update();
function update(){
if(d3.select("#myCheckbox").property("checked")){
newData = data.filter(function(d,i){return d % 2 == 0;});
} else {
newData = data;
}
newRows = table.selectAll("tr")
.data(newData,function(d){return d;});
newRows.enter()
.append("tr")
.append("td")
.text(function(d){return d;});
newRows.exit()
.remove();
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment