I have a set of input checkboxes with the same name and I would like to determine which checkboxes have been checked using javascript, how can I achieve that? I know only how to get all the checkboxes as follows:
var checkboxes = document.getElementsByName('mycheckboxes');
This question is related to
javascript
html
For a simple two- (or one) liner this code can be:
checkboxes = document.getElementsByName("NameOfCheckboxes");
selectedCboxes = Array.prototype.slice.call(checkboxes).filter(ch => ch.checked==true);
Here the Array.prototype.slice.call()
part converts the object NodeList of all the checkboxes holding that name ("NameOfCheckboxes") into a new array, on which you then use the filter method. You can then also, for example, extract the values of the checkboxes by adding a .map(ch => ch.value)
on the end of line 2.
The => is javascript's arrow function notation.
In IE9+, Chrome or Firefox you can do:
var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');
Get all the checked checkbox value in an array - one liner
const data = [...document.querySelectorAll('.inp:checked')].map(e => e.value);_x000D_
console.log(data);
_x000D_
<div class="row">_x000D_
<input class="custom-control-input inp"type="checkbox" id="inlineCheckbox1" Checked value="option1"> _x000D_
<label class="custom-control-label" for="inlineCheckbox1">Option1</label>_x000D_
<input class="custom-control-input inp" type="checkbox" id="inlineCheckbox1" value="option2"> _x000D_
<label class="custom-control-label" for="inlineCheckbox1">Option2</label>_x000D_
<input class="custom-control-input inp" Checked type="checkbox" id="inlineCheckbox1" value="option3"> _x000D_
<label class="custom-control-label" for="inlineCheckbox1">Option3</label>_x000D_
</div>
_x000D_
Source: Stackoverflow.com