Andrei CCL
Andrei CCL

Reputation: 103

Undefined result in Console by Input to Array Fields

Why when I pus the Submit button is undefined all of them?

I want to create an array just by using input fields like this.

Is there a nother way to do this?

I tried to do it with Class name and the result is still undefined

function clicked() {
    var input_value = document.querySelectorAll('#data, #data1, #data2, #data3, #data4').value;
    console.log(input_value)
}

document.getElementById('btn').addEventListener('click', clicked);
<input id="data">
<input id="data1">
<input id="data2">
<input id="data3">
<input id="data4">
<button id="btn">Click me</button>

Upvotes: 2

Views: 62

Answers (2)

bobbyz
bobbyz

Reputation: 5046

querySelectorAll will return a "NodeList", which is similar to an array. NodeLists don't have a value property, so it's returning undefined.

If you want to get the value from each of the input boxes, you'll need to loop through the NodeList and pull the value from each HTML element individually.

function clicked() {
    var nodeList = document.querySelectorAll('#data, #data1, #data2, #data3, #data4');
    for (var i = 0; i < nodeList.length; i++) {
      console.log(nodeList[i].value);
    }
}

document.getElementById('btn').addEventListener('click', clicked);

Upvotes: 3

anomaaly
anomaaly

Reputation: 841

Change fn to this:

function clicked() {
  var inputs= document.querySelectorAll('#data, #data1, #data2, #data3, #data4');
  inputs.forEach(i => {
    console.log(i.value);
  });
}

Upvotes: 0

Related Questions