Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I serializeArray for unchecked checkboxes?

Tags:

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] 
like image 923
BrunoLM Avatar asked Sep 07 '11 14:09

BrunoLM


People also ask

How do you send a value for a checkbox when it is unchecked?

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.

How do you force a checkbox to be selected by default?

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.


1 Answers

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.

like image 188
Pointy Avatar answered Oct 24 '22 03:10

Pointy