Submitting multiple inputs with same name

爱⌒轻易说出口 提交于 2019-12-07 15:15:47

问题


Ok, so I have form for creating polls. I want to use AJAX request and able user to attach image instead of question, so I use FormData for this.

I could't find any solution for working with multiple input with same name (named like this: "name[]"). I tried this option:

var fdata = new FormData();
fdata.append('answers[]', $('input[name="answer[]"]').val());

But it doesn't work. I know I could use .each(), but I don't want different name for each question, so I don't have to rebuild PHP side too much.

Thanks for any help.


回答1:


You have to append each value in turn. Currently you are only appending the first one (because that is what val() returns.

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



回答2:


The problem is $('input[name="answer[]"]').val() isn't giving you what you need; it returns the first input element's value. Instead, you want 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/



来源:https://stackoverflow.com/questions/31517875/submitting-multiple-inputs-with-same-name

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