So I have a dropdown list with checkboxes.
<div id = "dropdown" class ="dropdown">
<div class = "dropdown-row">
<label
<span class="text-space>Item 1</span>
<input type="checkbox" class="clickable">
</label>
</div>
<div class = "dropdown-row">
<label
<span class="text-space>Item 2</span>
<input type="checkbox" class="clickable">
</label>
</div>
<div class = "dropdown-row">
<label
<span class="text-space>Item 3</span>
<input type="checkbox" class="clickable">
</label>
</div>
<div class = "dropdown-row">
<label
<span class="text-space>Item 4</span>
<input type="checkbox" class="clickable">
</label>
</div>
<div class = "dropdown-row">
<label
<span class="text-space>Item 5</span>
<input type="checkbox" class="clickable">
</label>
</div>
<div class = "dropdown-row">
<label
<span class="text-space>Item 6</span>
<input type="checkbox" class="clickable">
</label>
</div>
</div>
I am trying to check if checkbox is checked and just simple text "Hi".
But it doesn’t work. I am not sure but I am trying to get all inputs with type="checkbox" and for each checkbox addEventListener on click.
const checkboxes = document.querySelectorAll('input[type="checkbox"]')
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener("click", function() {
if (checkboxes[i].checked) {
alert("Hi")
}
})
}
>Solution :
Add an event listener for the change event. It triggers whenever a checkbox is checked and unchecked. Use this.checked to verify if the checkbox is checked or not. Note that it is safe to use this keyword here because the function in addEventListener is a regular function and not an arrow function.
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener("change", function() {
if (this.checked) {
console.log(`Hi from Checkbox #${i + 1}`);
}
})
}
<div id="dropdown" class="dropdown">
<div class="dropdown-row">
<label>
<span class="text-space">Item 1</span>
<input type="checkbox" class="clickable">
</label>
</div>
<div class = "dropdown-row">
<label>
<span class="text-space">Item 2</span>
<input type="checkbox" class="clickable">
</label>
</div>
<div class = "dropdown-row">
<label>
<span class="text-space">Item 3</span>
<input type="checkbox" class="clickable">
</label>
</div>
<div class = "dropdown-row">
<label>
<span class="text-space">Item 4</span>
<input type="checkbox" class="clickable">
</label>
</div>
<div class = "dropdown-row">
<label>
<span class="text-space">Item 5</span>
<input type="checkbox" class="clickable">
</label>
</div>
<div class = "dropdown-row">
<label>
<span class="text-space">Item 6</span>
<input type="checkbox" class="clickable">
</label>
</div>
</div>