Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript querySelectorAll get multiple values from multiple inputs [duplicate]

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 :)

like image 872
merlijn merlin berg Avatar asked Mar 09 '26 18:03

merlijn merlin berg


2 Answers

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);
}
like image 94
Alnitak Avatar answered Mar 12 '26 06:03

Alnitak


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>
like image 25
Sankar Avatar answered Mar 12 '26 06:03

Sankar