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


You must add each value in turn. Currently you are only adding the first one (because that is what is returning val()

.



$('input[name="answer[]"]').each(function (index, member) {
    var value = $(member).val();
    fdata.append('answers[]', value);
});

      

+2


source


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);

      



http://jsfiddle.net/j5ezgxe9/

0


source







All Articles