Home > database >  Change variable value inside forEach
Change variable value inside forEach

Time:06-05

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.

CodePudding user response:

  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

CodePudding user response:

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" >
<input value="10" type="number" >
<input value="100" type="number" >

  • Related