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

213
Vistas
Change variable value inside forEach

I have three inputs and three variables, my goal is to change variables values with the values inside the inputs

const inputs = [
  document.querySelector(".bill-input"),
  document.querySelector(".custom"),
  document.querySelector(".people-number"),
];

var bill = 0;
var tip = 0;
var people = 0;

i accomplished to do it this way

inputs[0].addEventListener("keyup", (e) => {
  bill = Number(e.target.value);
});

inputs[1].addEventListener("keyup", (e) => {
  tip = Number(e.target.value);
});

inputs[2].addEventListener("keyup", (e) => {
  people = Number(e.target.value);
});

I'm pretty sure this is not the optimal way to do it, so i wanted to ask if there's a way to do it with forEach or any other method that does not require for me to write every single one each time.

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

0

  1. Add a data attribute to each input.
  2. Use an object to maintain the state of those inputs instead of n variables.
  3. Have one handler that can update the object properties based on their id.

// Initialise the values object
const values = { bill: 0, tip: 0, people: 0 };

// Cache the inputs, and add listeners to them
const inputs = document.querySelectorAll('input');
inputs.forEach(input => input.addEventListener('keyup', handleChange));

// Grab the id from the input's dataset, and
// set the values object property to match
// the input value
function handleChange() {
  const { id } = this.dataset;
  values[id] = this.value;
  console.log(JSON.stringify(values));
}
input { display: block; }
Bill<input data-id="bill">
Tip <input data-id="tip">
People <input data-id="people">

Additional documentation

  • Destructuring assignment
about 4 years ago · Juan Pablo Isaza Denunciar

0

Yes, you can use forEach. I used a switch to get the index of the input element (in inputs const) to know what variable update.

Please see snippet below :

var bill = 0;
var tip = 0;
var people = 0;
const inputs = [
  document.querySelector(".bill-input"),
  document.querySelector(".custom"),
  document.querySelector(".people-number"),
];
inputs.forEach(function(item,index){
  item.addEventListener("keyup", (e) => {
    const val = Number(e.target.value);
    switch(index){
      case 0 : bill = val; break;
      case 1 : tip = val; break;
      case 2 : people = val; break;
    }
    console.log(bill,tip,people)
  });
});
<input value="3" type="number" class="bill-input">
<input value="10" type="number" class="custom">
<input value="100" type="number" class="people-number">

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