marioizquierdo / jquery.serializeJSON

Serialize an HTML Form to a JavaScript Object, supporting nested attributes and arrays.
MIT License
1.72k stars 431 forks source link

Serializing empty array field #86

Closed zanderle closed 6 years ago

zanderle commented 6 years ago

Say you have a select element with no options selected:

<select name="myArray[]">
  <option value="1">1</option>
  <option value="2">2</option>
</select>

Would it be possible to have the result include an empty array? So something like:

$('select').serializeJSON({someOptionToControlThisBehavior: true});
// {myArray: []}

I'm also happy to do a PR if this is not implemented, if you just point me in the general direction.

marioizquierdo commented 6 years ago

This issue is duplicated of https://github.com/marioizquierdo/jquery.serializeJSON/issues/37

There's currently no option to identify empty select tags. But you can use an extra hidden field just like you would do with unchecked checkboxes:

<input name="myArray:array" type="hidden"  value="[]" />
<select name="myArray[]" multiple >
  <option value="1">1</option>
  <option value="2">2</option>
</select>
$('input,select').serializeJSON();