Javascript get form array values

家住魔仙堡 提交于 2020-12-03 05:35:59

问题


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


回答1:


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
}



回答2:


Simple approach:

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

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

    //your code goes here
}



回答3:


[...document.querySelector("#FORMID").elements['name[]']].map(el=>el.value); 
// Returns ["name","name",...]



回答4:


I think you can use document.getElementById('formIDhere').elements.name.

It will give you an array with all the values.




回答5:


your mistake is using getElementsByTagName, which is asking for a tag called <name>, and of course you don't have it, try setting a class to the input for example and fetch it using jquery $('className') which will surely get the result correct, or using dom you can still use document.getElementById('form').elements.name but still this way might not be cross browser safe unless tested carefully




回答6:


getElementsByTagName returns the array of elements whoose tag name is specified in argument. In html there is no element whoose tag name is name.

name is an attribute given to html elements. To get elements based on name you can use

var ele=document.getElementsByName('whatevername');

ele will contain the array of elements whose name is specified. Then you can use your loop to iterate through each element.




回答7:


this is what form elements is for

var inputs = document.getElementById('formIDhere').elements["name[]"];
alert(inputs.length);
for (i = 0; i < inputs.length; i++) {
    // your code here
}



回答8:


Using JQuery you could try:

   var arr = $('#frmId').serializeArray();

serialize method offers several options that you could check in: https://api.jquery.com/serializearray/



来源:https://stackoverflow.com/questions/19010177/javascript-get-form-array-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!