Search code examples
javascriptarraysvariablesforeachnumbers

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.


Solution

    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