javascriptarraysgetelementsbyname

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


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!!!


Solution

  • 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/