Home > Blockchain >  Change state of a checkbox with addEventListener in JavaScript
Change state of a checkbox with addEventListener in JavaScript

Time:10-17

I'm really new to JavaScript. I'm having some issues with my JavaScript code to change the state (checked or unchecked) of my checkbox input every time I click on an anchor element (the size and content is correct in CSS).

HTML simplified

<section>
  <a id="trigger"><img src="images/logo.png"></a>
  <input type="checkbox" id="nav-toggle">
</section>

JavaScript

let trigger = document.getElementById('trigger');
trigger.addEventListener('click', function() {
  let i = document.getElementById('nav-toggle');
  if(i.checked === false) {
     i.checked = true;
  } else {
    i.checked = false;
    }
  }
});

Let me know if my JavaScript code make sense, and what should I fix to make it work. Thanks!

CodePudding user response:

Just tried your code and it works fine, you've just put an extra curly brace on line 9

let trigger = document.getElementById('trigger');
trigger.addEventListener('click', function() {
  let i = document.getElementById('nav-toggle');
  if (i.checked === false) {
    i.checked = true;
  } else {
    i.checked = false;
  }
});
<section>
  <a id="trigger">toggle</a>
  <input type="checkbox" id="nav-toggle">
</section>

CodePudding user response:

If all you want to do is toggle the checkbox, don't use javascript, use the HTML label element and set the for attribute to the id of the checkbox.

<section>
  <label for="nav-toggle"><img src="images/logo.png" alt="alternate text"></label>
  <input type="checkbox" id="nav-toggle">
</section>

  • Related