Reputation: 31
I have a lot of input tags for the following form:
<input class="checkbox" type="checkbox" value="something_I_need_when_checked">
I need the value of all the checked boxes. When I call console.log(d3.selectAll("input.checkbox:checked").property("value"))
I only see the value of the first element. This post had some leads on how to change these values (EDIT: I don't want to change anything; I just want the values). I tried using the selection.each(function())
idea that was suggested but I didn't get me anywhere. How can I get all values in my selection.
I'm a n00b, be nice. Thanks ~
Upvotes: 2
Views: 2322
Reputation: 173
Another way to get the fields into an array is to use the map
function. In the example below, I build off of Gerardo Furtado's answer.
d3.select("button").on("click", function() {
var checkedBoxes = d3.selectAll("input.checkbox:checked").nodes().map(box => box.value);
console.log(checkedBoxes)
});
<script src="https://d3js.org/d3.v5.js"></script>
<input class="checkbox" type="checkbox" value="foo">foo
<input class="checkbox" type="checkbox" value="bar">bar
<input class="checkbox" type="checkbox" value="baz">baz
<input class="checkbox" type="checkbox" value="foobar">foobar
<input class="checkbox" type="checkbox" value="foobaz">foobaz
<button>Check</button>
Upvotes: 0
Reputation: 102174
selection.each
does work. However, you have to call it after clicking the checkboxes.
In this demo, the selection will be created after you click the button named "Check". Click the boxes you want, and after that click the button:
d3.select("button").on("click", function() {
var boxes = d3.selectAll("input.checkbox:checked");
boxes.each(function() {
console.log(this.value)
})
});
<script src="https://d3js.org/d3.v4.js"></script>
<input class="checkbox" type="checkbox" value="foo">foo
<input class="checkbox" type="checkbox" value="bar">bar
<input class="checkbox" type="checkbox" value="baz">baz
<input class="checkbox" type="checkbox" value="foobar">foobar
<input class="checkbox" type="checkbox" value="foobaz">foobaz
<button>Check</button>
EDIT: storing the checked values in an array:
var checked = [];
d3.select("button").on("click", function() {
var boxes = d3.selectAll("input.checkbox:checked");
boxes.each(function() {
checked.push(this.value)
});
console.log(checked)
});
<script src="https://d3js.org/d3.v4.js"></script>
<input class="checkbox" type="checkbox" value="foo">foo
<input class="checkbox" type="checkbox" value="bar">bar
<input class="checkbox" type="checkbox" value="baz">baz
<input class="checkbox" type="checkbox" value="foobar">foobar
<input class="checkbox" type="checkbox" value="foobaz">foobaz
<button>Check</button>
Upvotes: 2