Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

139
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda