0

I have this JS:

let streetNumber = document.getElementById('street_number').value;
let postalCode = document.getElementById('postal_code').value;
let country = document.getElementById('country').value;

But it's very repetitive and not really DRY in my opinion. What I would love is something like this (because I have the array available):

let arr = ["street_number", "postal_code", "country"];

for (entry of arr) {
   let entry = document.getElementById(entry).value;
}

Basically just creating JS variables for each of the input values extracted from the HTML input field.

How can I achieve this?

Raf Rasenberg
  • 534
  • 2
  • 14
  • 27
  • you can use getElementsByTagName("input") to get all the input fields. – adarsh Jun 12 '20 at 07:53
  • You can't create a variable whose name comes from a runtime value. The usual solution here is to use an object or a `Map`: `const inputs = Object.fromEntries(arr.map(name => [name, document.getElementById(name).value]));` or `const inputs = new Map(arr.map(name => [name, document.getElementById(name).value]));` – T.J. Crowder Jun 12 '20 at 07:54

0 Answers0