Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript get form array values

I have a form that is set up so that there is an add button so my user can submit multiple people at once to the site.

At first the form has an input to fill out the persons name one example below

<input type="text" name="name[]" value="Name" /> 

If they hit the add button another one is appended so that I'm left with the following

<input type="text" name="name[]" value="Name" /> 
<input type="text" name="name[]" value="Name" /> 

Then when they hit submit I'm trying to get the values of each name in Javascript and loop through them I've tried this but it's not working

var inputs = document.getElementById('formIDhere').getElementsByTagName('name');
alert(inputs.length);

I never get the alert and if I just set up a loop like this

for(int i=0; i<inputs.length; i++)

Nothing happens, any help on looping through the values of name[] in javascript would be greatly appreciated

like image 767
user577732 Avatar asked Sep 25 '13 16:09

user577732


3 Answers

I guess you could try:

var inputs = document.querySelectorAll("#formIDHere input[name='name[]']");
alert(inputs.length);
for (i = 0; i < inputs.length; i++) {
    // your code here
}
like image 56
Duncan Avatar answered Nov 11 '22 00:11

Duncan


Simple approach:

var names=document.getElementsByName('name[]');

for(key=0; key < names.length; key++)  {
    alert(names[key].value);

    //your code goes here
}
like image 20
Biswadeep Sarkar Avatar answered Nov 10 '22 23:11

Biswadeep Sarkar


[...document.querySelector("#FORMID").elements['name[]']].map(el=>el.value); 
// Returns ["name","name",...]
like image 32
Анатолій ЖелезнЫйквадрат Avatar answered Nov 10 '22 23:11

Анатолій ЖелезнЫйквадрат