Search code examples
javascriptjqueryforms

How can I serializeArray for unchecked checkboxes?


How can I modify this example so it can get values from checkboxes that aren't checked?

I want all checkboxes to have a value, if it hasn't been checked I want to get its value as false.

<input type="checkbox" name="Check01" value="true" />
<input type="checkbox" name="Check02" value="true" checked="checked" />

Default behavior

$("form").serializeArray();
// [Check02 = true]

Expected behavior

$("form").serializeArray();
// [Check01 = false, Check02 = true]

Solution

  • It's probably easiest to just do it yourself:

     var serialized = $('input:checkbox').map(function() {
       return { name: this.name, value: this.checked ? this.value : "false" };
     });
    

    If there are other inputs, then you could serialize the form, and then find the unchecked checkboxes with something like the above and append that result to the first array.