JavaScript Checkbox Event Handler

How can i fire an event when a checkbox is checked or unchecked in JavaScript?

I have a checkbox. When I check it, I want the variable productionState to be set to true, and when I uncheck, I want it back to false. What I have doesn’t work. Am I missing something? 

HTML

<div class="form-check ">

<input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">

<label class="form-check-label" for="flexCheckDefault">

Production State

</label>

</div>

JavaScript

let productionState = false

const checkbox = document.getElementById("flexCheckDefault");

checkbox.addEventListener("change", (event) => (productionState = true));

>Solution :

Maybe this is what you are looking for?

let productionState=false;
document.getElementById("flexCheckDefault").addEventListener("change",ev => console.log(productionState=ev.target.checked));
<div class="form-check ">
<input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
<label class="form-check-label" for="flexCheckDefault">Production State</label>
</div>

Leave a Reply