Home > Blockchain >  Why don't JavaScript properties update automatically?
Why don't JavaScript properties update automatically?

Time:10-27

I have an object with a property that stores the checked property of a checkbox like so:

var x = {
  isChecked: document.querySelector("input").checked
};


function getX() {
  (x.isChecked ? console.log("checkbox is checked") : console.log("checkbox is not checked"));
}
<input type="checkbox">
<button onclick="getX()">is the checkbox checked?</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

When checking and unchecking the checkbox, the isChecked property's value doesn't update. Why might that be?

CodePudding user response:

Since .checked is a boolean, not an object, when you say isChecked: document.querySelector("input").checked, you're just setting isChecked to the current value of element.checked. Make isChecked a function to get the actual value every time you need it.

var x = {
  isChecked: () => document.querySelector("input").checked
};


function getX() {
  (x.isChecked() ? console.log("checkbox is checked") : console.log("checkbox is not checked"));
}
<input type="checkbox">
<button onclick="getX()">is the checkbox checked?</button>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Alternatively, if you want to continue using it with isChecked and not isChecked(), and you want to be able to set it manually with that variable, you can use getters and setters like this:

var x = {
  get isChecked() {
    return document.querySelector("input").checked;
  },
  
  set isChecked(checked) {
    return document.querySelector("input").checked = checked;
  }
};


function getX() {
  (x.isChecked ? console.log("checkbox is checked") : console.log("checkbox is not checked"));
}
<input type="checkbox">
<button onclick="getX()">is the checkbox checked?</button>
<button onclick="x.isChecked = false">uncheck</button>
<button onclick="x.isChecked = true">check</button>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related