You should listen for the "change" event on checkboxes, rather than
"click". It's possible to toggle a checkbox without clicking, say by
focusing it using the tab key and hitting return. (Though some
browsers, including Chrome, map this to click anyway. So it's not
critical, but still a good practice.)
When you receive the "change" event, you can then inspect the state of
the checkbox by looking at `this.checked`. When the event handler is
called, `this` is the element that received the event—an input element
of type "checkbox". The `checked` property is a boolean that says
whether or not the checkbox is checked:
http://www.w3.org/TR/html5/the-input-element.html#attr-input-checked
You use this boolean to determine the appropriate value of the
"display" style, which should be "none" for hidden circles and null
(the default) for visible circles. I like using JavaScript's question
mark (ternary) operator for this purpose.
Your logic needs a bit of tweaking if you want the blue checkbox to
cause only blue circles to be visible: you need to make sure that if
the blue circles were hidden previously, they become visible. Radio
buttons make more sense in this case, because the inputs are
exclusive: you can't show *only* blue and *only* red at the same time.
So, if you had:
<input id="blue" type="radio" name="color" value="blue">
<label for="blue">Blue</label>
<input id="red" type="radio" name="color" value="red">
<label for="red">Red</label>
<input id="both" type="radio" name="color" value="both">
<label for="both">Both</label>
Then you might say:
d3.selectAll("input[name=color]").on("change", colorchange);
Where:
function colorchange() {
var color = this.value;
vis.selectAll(".ball")
.style("display", function(d) { return d.color == color ? null
: "none"; });
}
Note that I capture the `this.value` in a local variable so that it's
accessible from within the style function.
Alternatively, you could keep the checkboxes, but have them both
checked by default and have them control the visibility of their own
color independently. (But, it's then possible to uncheck both and hide
everything.)
function toggleBlue() {
vis.selectAll(".ball")
.filter(function(d) { return d.color == "blue"; })
.style("display", this.checked ? null : "none");
}
Mike