I’m using jQuery.serialize to retrieve all data fields in a form.
My problem is that it does not retriev checkboxes that is not checked.
It includes this:
<input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" checked="checked" />
but not this
<input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" />
How can I get “values” of checkboxes that is not checked?
jQuery
serializeclosely mimics how a standard form would be serialized by the browser before being appended to the query string or POST body in the request. Unchecked checkboxes aren’t included by the browser, which makes sense really because they have a boolean state — they’re either selected by the user (included) or not selected by the user (not included).If you need it to be in the serialized, you should ask yourself “why? why not just check for its existence in the data?”.
Bear in mind that if the way JavaScript serializes form data behaves differently to the way the browser does it then you’re eliminating any chance of graceful degradation for your form. If you still absolutely need to do it, just use a
<select>box with Yes/No as options. At least then, users with JS disabled aren’t alienated from your site and you’re not going against the defined behaviour in the HTML specification.I’ve seen this employed on some sites in the past and always thought to myself, “why don’t they just use a checkbox”?