Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery serialize does not register checkboxes

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?

like image 406
Steven Avatar asked Jun 12 '10 19:06

Steven


2 Answers

To build on azatoth's genius answer, I have slightly extended it for my scenario:

    /* Get input values from form */     values = jQuery("#myform").serializeArray();      /* Because serializeArray() ignores unset checkboxes and radio buttons: */     values = values.concat(             jQuery('#myform input[type=checkbox]:not(:checked)').map(                     function() {                         return {"name": this.name, "value": false}                     }).get()     ); 
like image 167
mydoghasworms Avatar answered Oct 09 '22 07:10

mydoghasworms


jQuery serialize closely 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.

<select id="event_allDay" name="event_allDay">    <option value="0" selected>No</option>    <option value="1">Yes</option> </select> 

I've seen this employed on some sites in the past and always thought to myself, "why don't they just use a checkbox"?

like image 28
Andy E Avatar answered Oct 09 '22 07:10

Andy E