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

127
Vistas
Update variable within JavaScript object

Here's a simplified example of something I'm trying to do.

I've got an input field which I need to get the value from when the user types in his name and click the "Save changes" button.

What I then need is for the username variable to update accordingly to what the user typed in. The page has localization features which complicate things slightly. I can't seem to populate the updated value within the translations object (anywhere username is mentioned, the initialized value is retained and not the last assigned one). This is the part I'm struggling with.

Here's my code:

var p = document.querySelectorAll("p")[0];
var input = document.querySelectorAll("input")[0];
var button = document.querySelectorAll("button")[0];

var locale = "en";
var username = "";

button.onclick = function() {
  username = input.value;
  document.querySelectorAll("[data-language-key]").forEach(translate);
}

function translate(element) {
  const key = element.getAttribute("data-language-key");
  const translation = translations[locale][key];
  element.innerText = translation;
}

var translations = {
  "en": {
    "message": `Good morning, ${username}!`,
  },
  "fr": {
    "message": `Bonjour, ${username} !`,
  }
}
body {
  background-color: gray;
}

button {
  margin: 200px;
}
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>
</head>

<body>

  <p data-language-key="message">Good morning, {username}!</p>
  <input type="text" placeholder="Type your name...">
  <button>Save changes</button>

</body>

</html>

JavaScript beginner here (if you can ELI5 your answer, I'd appreciate greatly!)

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

As suggested in the comments, the variable is substituted when the literal is read, therefore we postpone the reading until it's actually needed. This is done using a function.

var p = document.querySelector("p");
var input = document.querySelector("input");
var button = document.querySelector("button");

var locale = "en";
var username = "";

button.onclick = function() {
  username = input.value;
  translate(document.querySelector("[data-language-key]"));
}

function translate(element) {
  var key = element.getAttribute("data-language-key")
  const translation = translations[locale][key];
  var text = translation(username);
  element.innerText = text;
}

var translations = {
  "en": {
    "message": () => `Good morning, ${username}!`,
  },
  "fr": {
    "message": () => `Bonjour, ${username} !`,
  }
}
<p data-language-key="message">Good morning, {username}!</p>
<input type="text" placeholder="Type your name...">
<button>Save changes</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