ueeiee ueeiee - 2 months ago 8
Javascript Question

I try to assign an arraylike collection of elements to variables, whats wrong with my code?

I try to run a forEach loop on inputs and assign each of the elements into some variables, but something doesn't work properly.

not sure why my variables are keep being "not defined".

js file:

var inputs = document.querySelectorAll("input[type=text]");

inputs.forEach(function(item, index, array){

var inputName, inputLastName, inputAge;

if(array[index].name === "name"){
inputName = array[index];
}
if(array[index].name === "lastName"){
inputLastName = array[index];
}
if(array[index].name === "age"){
inputAge = array[index];
}
});


html file:

<form action="">
<label for="name"> Name:
<input type="text" name="name">
</label>

<label for="lastName"> Last Name:
<input type="text" name="lastName">
</label>

<label for="age"> Age:
<input type="text" name="age">
</label>
</form>

Answer

Your actual code is working perfectly, expect that you are making your inputName, inputLastName, inputAge variables local to the foreach loop so they won't be accessible outside it.

You need to declare them outside the loop. This is a working snippet:

var inputs = document.querySelectorAll("input[type=text]");

var inputName, inputLastName, inputAge;

inputs.forEach(function(item, index, array) {


  if (item.name === "name") {
    inputName = array[index];
  }
  if (item.name === "lastName") {
    inputLastName = array[index];
  }
  if (item.name === "age") {
    inputAge = array[index];
  }
});

console.log(inputName);
<label for="name">Name:
  <input type="text" name="name">
</label>

<label for="lastName">Last Name:
  <input type="text" name="lastName">
</label>

<label for="age">Age:
  <input type="text" name="age">
</label>

You can also use item.nameinstead of array[index].name to get the current iterated element.

Comments