javascript: document.getElementsByName("sample[]") not working

1.1k Views Asked by At

I have a form where you can append additional input if needed. So I named my form like this.

<input type="text" name="sample[]" />

I want to access all the value of the inputs with a name "sample[]" and store it in an array using javascript. I used this code below:

 var sample = document.getElementsByName(sample[]);

How can I get all the values individually? Any help would be greatly appreciated. Thank you!!!

5

There are 5 best solutions below

2
On BEST ANSWER

Add this to your js function and you will get input values in values array. Here I am getting a NodeList of all elements with name = "sample[]" and converting to Array for easy processing of data.

var sample = Array.prototype.slice.call(document.getElementsByName('sample[]'));
var values = sample.map((o) => o.value);

Tested it and following is the link to fiddle. https://jsfiddle.net/mfw4rv9o/13/

0
On

String value 'sample[]' is totally different from eval value of sample[]. Hence is the confusion over all. If you're very sure you want to pass 'sample[]' as a (string) value of name prop of , make sure you stringify it and add it.

2
On

var sample = document.getElementsByName('sample[]');
Add quotes between sample[]. Try to avoid [] in input name.

0
On

The name of the input is name="sample[]". The parameter of getElementsByName is the value of the name attribute of the element(s) so that should be "sample[]".

getElementsByName will return a NodeList for which you could use a foreach to loop over, use item to return a node from a NodeList by index or use an index sample[0].

To get all the values in an array in es6 you could use the spread operator and map:

let items = [...document.getElementsByName("sample[]")].map(i => i.value);

var sample = document.getElementsByName("sample[]");
console.log(sample[0].value);
console.log(sample.item(0).value);
let items = [...document.getElementsByName("sample[]")].map(i => i.value);
console.log(items);
<form>
  <input type="text" name="sample[]" value="value1" />
  <input type="text" name="sample[]" value="value2" />
</form>

0
On

In ES6:

var values = [...document.querySelectorAll("input[name='sample[]']")].map(x => x.value);

But I would refrain from using sample[] as the input name.