Using an array to store the values of the checked checkboxes lets you query that list for filtering pretty easily.
Last active
October 15, 2023 16:59
-
-
Save johnnygizmo/531991a77047112b7ca89f78b840fba5 to your computer and use it in GitHub Desktop.
Multiple Checkbox Filtering
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
height: 200 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<script src="https://d3js.org/d3.v4.0.0-alpha.40.min.js"></script> | |
</head> | |
<body> | |
<input type="checkbox" class="myCheckbox" value="thor"> test 1 (thor) | |
<input type="checkbox" class="myCheckbox" value="spiderman"> test 2 (spiderman) | |
<input type="checkbox" class="myCheckbox" value="superman"> test 3 (superman) | |
<div id="content"></div> | |
<script> | |
data = ["batman","thor","superman","spiderman","ironman"]; | |
table = d3.select("#content") | |
.append("table") | |
.property("border","1px"); | |
d3.selectAll(".myCheckbox").on("change",update); | |
update(); | |
function update(){ | |
var choices = []; | |
d3.selectAll(".myCheckbox").each(function(d){ | |
cb = d3.select(this); | |
if(cb.property("checked")){ | |
choices.push(cb.property("value")); | |
} | |
}); | |
if(choices.length > 0){ | |
newData = data.filter(function(d,i){return choices.includes(d);}); | |
} 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