form-serialize icon indicating copy to clipboard operation
form-serialize copied to clipboard

{ hash: true, empty: true } yields empty values for `name[]` (no index)

Open nhunzaker opened this issue 9 years ago • 2 comments

I'm working on an app with the following inputs:

<input type="checkbox" name="types[]" value="activities" checked />
<input type="checkbox" name="types[]" value="games" />
<input type="checkbox" name="types[]" value="apps" />
<input type="checkbox" name="types[]" value="videos" checked />

I'm using { hash: true, empty: true } so that I can serialize down an empty types field. However the inputs that aren't checked are showing up in the serialized parameters like:

{
    "types": ["", "activities", "", "videos" ]
}

I would like:

{
    "types": ["activities", "videos" ]
}

and the following when no inputs are checked:

{
    "types": []
}

What do you think about stripping out unchecked boxes if the name field includes no index?

nhunzaker avatar Jul 21 '16 14:07 nhunzaker

Seems pretty reasonable if right now it just returns empty strings for those fields. What is the equivalent form-encoding string for the above input (i.e. when hash: false is used)

defunctzombie avatar Jul 22 '16 03:07 defunctzombie

A quick test shows that it only includes the checked values, using:

<form action="/" method="POST">
  <input type="checkbox" name="types[]" value="activities" checked />
  <input type="checkbox" name="types[]" value="games" />
  <input type="checkbox" name="types[]" value="apps" />
  <input type="checkbox" name="types[]" value="videos" checked />
  <button type="submit">Go</button>
</form>

If I inspect the networking tab, only the checked inputs are included:

screen shot 2016-08-15 at 7 59 51 pm

I'll jam on this a bit and send out a PR.

nhunzaker avatar Aug 16 '16 00:08 nhunzaker