// Get all input fields
const allInputs = Array.from(document.querySelectorAll('input'));
// Whenever any input field change
const handleInputChange = e => {
// Create a values array for each checked input
const values = allInputs.reduce((acc, input) =>
// If field is checked
input.checked
// Add its label content to values array
? [...acc, document.querySelector(`label[for="${input.id}"]`).textContent]
// Or return return previous array
: acc, []);
console.log(values);
};
// Bind event on all input fields
allInputs.forEach(input => input.addEventListener('change', handleInputChange));
<div class="col-6 col-12-small">
<h4>Document Submited</h4>
<input type="checkbox" id="idcopy" name="checkbox">
<label for="idcopy">NIC Copy</label>
<input type="checkbox" id="birthcertificate" name="checkbox">
<label for="birthcertificate">Birth Certificate</label>
<input type="checkbox" id="nomineeNic" name="checkbox">
<label for="nomineeNic">Nominee NIC copy</label>
<input type="checkbox" id="agreement" name="checkbox">
<label for="agreement">Agreement</label>
</div>
You may also have reusable function like:
const getLabel = (labelFor, rootElement = document) =>
rootElement.querySelector(`label[for="${labelFor}"]`);
// Or to get text content directly:
const getLabel = (labelFor, rootElement = document) =>
(rootElement.querySelector(`label[for="${labelFor}"]`) || {}).textContent;
// Boolean || is there to avoid throwing error when no matching label found in DOM
Although, for simpler code you may put the data you want to get from checkboxes either directly in checkbox attribute (like: <input type="checkbox" id="myId" data-myCustomData="My data if box is checked" />
), or in a JS object:
const myData = {
checkboxId1: "Data for first checkbox foo",
checkboxId5: "Data for first checkbox bar",
};