-1

When trying to use the ".checked" property, it does not return a true value and therefore I cannot get this test code to alert when checkbox is checked.

var lower = document.querySelector("#lower");

if (lower.checked === true) {
    alert('CHECKED!');
}
<li><label for="lower"><input type="checkbox" id="lower">lowercase</label></li>

I also tried the following javascript:

var lower = document.querySelector("#lower");

if (lower.checked) {
    alert('CHECKED!');
}

also tried it with document.getElementById("lower"). Any ideas?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
bigcat86
  • 1
  • 1
  • 1
    How are you calling the code? If it's just at top-level, it runs when the page loads, before the user has had a chance to check the box. You need to put it in an event listener that runs when the user does something. – Barmar Mar 08 '23 at 17:11
  • It won't run by itself when the user checks the box. – Barmar Mar 08 '23 at 17:12
  • Your code thinks the checkbox isn't checked because at the time the javascript runs (on page-load), it _isn't_ checked! – Pranav Hosangadi Mar 08 '23 at 17:12
  • If you are running this code after user has checked the box, it will not work. `.checked` returns the state of the input when the page loads. Any interaction on it after the page load, will not update this property. Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox#additional_attributes – Prerak Sola Mar 08 '23 at 17:12
  • @PrerakSola more specifically, an interaction on it after the page loads *will* update the property, but the code that initially checked it's value won't re-run on it's own. – Kevin B Mar 08 '23 at 17:21

2 Answers2

1

You need to catch an event for clicking.

By loading the page, the box is not checked.

var lower = document.querySelector("#lower");

lower.addEventListener('click', () => {
    if (lower.checked) console.log('CHECKED!');
});
<li><label for="lower"><input type="checkbox" id="lower">lowercase</label></li>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Add an event listener for the "change" event in order to have your code run each time the checkbox's state changes.

document.querySelector("#lower").addEventListener('change', function(e) {
  if (this.checked) console.log('CHECKED');
});
<li><label for="lower"><input type="checkbox" id="lower">lowercase</label></li>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80