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

214
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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