18

My html form has multiple checkboxes with the same name attribute:

<form id='cheese-selector'>
  <input type="checkbox" name="cheese" id="limburger" value="Limburger">Limburger</input>
  <input type="checkbox" name="cheese" id="camembert" value="Camembert">Camembert</input>
  <input type="checkbox" name="cheese" id="roquefort" value="Roquefort">Roquefort</input>
  <input type="submit" id="pick-cheese">Pick My Cheese!</input>
</form>

I'm submitting it via ajax. When I make a FormData object, only the first selected checkbox is included, even if I've checked more than one:

$('#limburger').click()
$('#camembert').click()
console.log(FormData(this).get('cheese'))
// 'Limburger'

How do I make FormData encode all the checked values as an array?

2 Answers 2

19

See MDN:

The get() method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead.

Sign up to request clarification or add additional context in comments.

4 Comments

So, reliably getting all the data from unknown HTML forms, in the same form that a web browser would submit it, is not trivial with FormData.
@PaulD.Waite — No. Just use getAll.
@Plummer — The use case in the question calls for only sending the data for the checked checkboxes.
@Quentin in terms of the original question, yes. I was relaying context in regard to the client.
0

Expanding on the discussion in comments to the accepted answer, FormData methods don't return checkbox inputs if they are not checked.

This is true for entries(), getAll(), and keys().

has() also will return false for a name if it is not checked. If a consumer doesn't have reference to the form schema, then FormData will not return any unchecked checkbox input names.

One way around this would be to add a <input type="hidden" /> with the same name as the checkbox group. This would reliably ensure that the field key would be present.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.