Home > Software engineering >  JavaScript Checkbox Event Handler
JavaScript Checkbox Event Handler

Time:06-17

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 >

<input  type="checkbox" value="" id="flexCheckDefault">

<label  for="flexCheckDefault">

Production State

</label>

</div>

JavaScript

let productionState = false

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

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

CodePudding user response:

let productionState = false

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

checkbox.addEventListener("change", (event) => {
productionState = checkbox.checked;
});

CodePudding user response:

Maybe this is what you are looking for?

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

  • Related