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
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
}
Simple approach:
var names=document.getElementsByName('name[]');
for(key=0; key < names.length; key++) {
alert(names[key].value);
//your code goes here
}
[...document.querySelector("#FORMID").elements['name[]']].map(el=>el.value);
// Returns ["name","name",...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With