Sasgorilla
Sasgorilla

Reputation: 3130

How do I get multiple checkbox values in FormData?

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?

Upvotes: 17

Views: 10301

Answers (1)

Quentin
Quentin

Reputation: 943579

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.

Upvotes: 20

Related Questions