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]
If you wanted to submit a default value for the checkbox when it is unchecked, you could include an <input type="hidden"> inside the form with the same name and value , generated by JavaScript perhaps.
When rendering a page with a checkbox you want selected or checked by default you need to include the 'checked' attribute. There is no required value for the checked attribute. However, per the checkbox specification only an empty value or 'checked' are valid.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With