Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
Why don't JavaScript properties update automatically?

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>

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda