Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submitting multiple inputs with same name

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.

like image 256
r34 Avatar asked Jul 20 '15 13:07

r34


People also ask

Can multiple inputs have same name?

inputs with the same name is the same form are part of the HTML standard - they are used, e.g., for checkboxes. It is valid to place multiple inputs (hidden or otherwise) with the same name within a single form.

How do you take multiple inputs in a form?

Tip: For <input type="file"> : To select multiple files, hold down the CTRL or SHIFT key while selecting. Tip: For <input type="email"> : Separate each email with a comma, like: [email protected], [email protected], [email protected] in the email field.

Can multiple inputs have the same ID HTML?

The HTML id attribute is used to specify a unique id for an HTML element. You cannot have more than one element with the same id in an HTML document.

Can different HTML elements have the same name?

Different Elements Can Share Same ClassDifferent HTML elements can point to the same class name.


1 Answers

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);
});
like image 98
Quentin Avatar answered Oct 19 '22 14:10

Quentin