3

I am making a website and I want to use multiple inputs

<input type="text" class="foo" value="foo">
<input type="text" class="foo" value="foo">
<input type="text" class="foo" value="foo">
...

<button onclick="function()">Send</button>

In the Javascript I am using a querySelectorAll to get the values in a array

function function() {
   document.querySelectorAll('.foo').value;
}

This only work for me when I don’t use a value but then I get the full element and not the value..

Thanks :)

4 Answers4

7

document.querySelectorAll() returns a (non-live) NodeList, not an array. Fortunately it is possible to call the array methods on pseudo-arrays:

function getValues(selector) {
    var els = document.querySelectorAll(selector);
    return [].map.call(els, el => el.value);
}
Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

document.querySelectorAll('.foo') will return nodeList. So your code will return undefined.

one of the way, you can get array of values.

function func() {
  var a = document.querySelectorAll('.foo');
  var b = [];
  for(var i = 0; i <= a.length-1; i++){
    b.push(a[i].value);
  }
  console.log(b);
}
<input type="text" class="foo" value="foo">
<input type="text" class="foo" value="foo">
<input type="text" class="foo" value="foo">

<button onclick="func()">Send</button>
Sankar
  • 6,908
  • 2
  • 30
  • 53
  • `.forEach` combined with `push` is a classic anti-pattern (notwithstanding that the `NodeList` interface does offer `.forEach` but doesn't directly support `.map`) – Alnitak May 16 '17 at 09:11
  • @Alnitak can you explain sorry, i don't understand – Sankar May 16 '17 at 09:16
  • The canonical way to take an array of something and pass every element through a mutating function, returning a new array of the results is `Array.prototype.map` – Alnitak May 16 '17 at 09:33
  • @Alnitak Got it. thanks – Sankar May 16 '17 at 09:35
  • @KadenSkinner, you are trying to check if two array is equal, so this might help - `JSON.stringify(b)==JSON.stringify(["", "foo", "foo"]);` – Sankar May 03 '21 at 18:54
0

You need to access the values individually. Here is your updated code as an example:

function myfunc() {
   var myElementArray = document.querySelectorAll('.foo');

     var myOutputText = "";
     for(var i=0;i< myElementArray.length; i++){
            myOutputText += myElementArray[i].value + " | ";
    }

    alert(myOutputText);
}

Here is the JSFiddle demo

Ahs N
  • 8,233
  • 1
  • 28
  • 33
-1

With ES6, to get an array of values you can try this

Array.from(document.querySelectorAll('.foo')).map(x => x.value)
Tai Dinh
  • 33
  • 2
  • 7
  • I considered doing that in my own answer, but it unnecessarily creates a whole new array only to throw it away again. Using `[].map.call` avoids that step. – Alnitak May 16 '17 at 09:32