Sending multiple inputs with the same name
Ok, so I have a form to create polls. I want to use an AJAX request and a capable user to attach an image instead of a question, so I am using FormData for that.
I couldn't find a solution to deal with multiple inputs with the same name (named like this: "name []"). I tried this option:
var fdata = new FormData();
fdata.append('answers[]', $('input[name="answer[]"]').val());
But that won't work. I know what I could use .each()
, but I don't want to have a different name for each question, so I don't need to rebuild the PHP server too much.
Thanks for any help.
+3
source to share
2 answers
The problem is $('input[name="answer[]"]').val()
not giving you what you need; it returns the value of the first input element. Instead, you want to get an array of values:
var values = [];
$('input[name="answer[]"]').each(function(i, item) {
values.push(item.value);
});
fdata.append('answers[]', values);
0
source to share