7

I have an HTML form with some checkboxes. I use jQuery .serialize() function to make a query string to submit to the database. The problem I am having is that when a checkbox is unchecked, the .serialize() function does not register it in the query string.

My problem is illustrated in this jsfiddle: http://jsfiddle.net/cTKhH/.

This is a problem because i still need to save a value of the unchecked check box to the database. Right now the information is only saved when the check box is checked. When it is unchecked, and the information from .serialize() is submitted, no change is made since there is no information submitted.

Does anyone know how to make my .serialize() function return the unchecked value for all check boxes when they are unchecked?

Thanks!!

** EDIT **

Just a little more info, I know now why the unchecked check box is not submitted, because it is not a "successful" form control, see here: http://www.w3.org/TR/html401/interact/forms.html#successful-controls.

Hopefully I still modify the .serialize() function to submit unchecked values.

6
  • 2
    If it's unchecked it's not submitted, that's how checkboxes work. Might need to change your methodology here.
    – MetalFrog
    Commented Apr 26, 2012 at 19:18
  • @MetalFrog - Yeah that makes sense. I need to think about how I will do that. Commented Apr 26, 2012 at 19:41
  • If you're just doing simple yes/no checkboxes, use radios instead, with a default radio checked on load. Or, on the server side, check if the option is set or not. If it is not set, use whatever you need to in order to fulfill your requirements. If it is set, use the posted value.
    – MetalFrog
    Commented Apr 26, 2012 at 19:56
  • @jeffery_the_wind I tried to customize jQuery serializeArray function as per your need. Take a look and let me know if it works for you. Commented Apr 26, 2012 at 20:06
  • stackoverflow.com/questions/3029870/…
    – ScottE
    Commented Apr 26, 2012 at 20:16

6 Answers 6

4

Here is a simple example - I'm sure you could wrap this into a nice plugin.

html

<form id="doit" action="" method="post">    
    <input type="checkbox" name="test" data-checkedName="test" data-uncheckedid="yup" value="true" class="checkedValue" />
    <input type="hidden" name="test" id="yup" value="false" />
    <input type="submit" value="serialize" />
</form>

js

$(function () {

    $(".checkedValue").click(function () {

        var $cb = $(this),
            $associatedHiddenField = $("#" + $cb.attr("data-uncheckedid")),
            name = $cb.attr("data-checkedName");

        if (this.checked) {
            $cb.attr("name", name);
            $associatedHiddenField.removeAttr("name");

        } else {
            $cb.removeAttr("name");
            $associatedHiddenField.attr("name", name);
        }

    });

    $("#doit").submit(function (e) {
        e.preventDefault();
        console.log($(this).serialize());
    });
});
2

Description

jQuery.serialize() almost doing the same as the browser then you submit a form. Unchecked checkboxes are not included in a form submit.

A workarount is to use a select element.

Check out my sample and this jsFiddle Demonstration

Sample

<form>
<select id="event_allDay" name="a">
   <option value="0" selected>No</option>
   <option value="1">Yes</option>
</select>
</form>
<button id="b">submit</button>​


$('#b').click(function() {
    alert($('form').serialize());
});​

Edit

I dont know if and what server technology you are using. But if you use one, you can fix that using default values too.

3
  • @Vega depends on how the "checkboxes" are created. ;)
    – dknaack
    Commented Apr 26, 2012 at 19:26
  • Yeah, thanks for the workaround, but visually and interactively i prefer a checkbox... will probably have to fix this in the code. Commented Apr 26, 2012 at 19:40
  • @jeffery_the_wind i dont know if and what server technology you are using. But if you use one, you can fix that using default values. Glad to help!
    – dknaack
    Commented Apr 26, 2012 at 19:49
2

You can probably customize the serializeArray function in jQuery allowing to include checkbox if not set.

DEMO

NOTE: Below is just a rough draft, please feel free to optimize.

$.fn.serializeArray = function () {
    var rselectTextarea= /^(?:select|textarea)/i;
    var rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i;
    var rCRLF = /\r?\n/g;

    return this.map(function () {
        return this.elements ? jQuery.makeArray(this.elements) : this;
    }).filter(function () {
        return this.name && !this.disabled && (this.checked || rselectTextarea.test(this.nodeName) || rinput.test(this.type) || this.type == "checkbox");
    }).map(function (i, elem) {
        var val = jQuery(this).val();
        if (this.type == 'checkbox' && this.checked === false) {
            val = 'off';
        }
        return val == null ? null : jQuery.isArray(val) ? jQuery.map(val, function (val, i) {
            return {
                name: elem.name,
                value: val.replace(rCRLF, "\r\n")
            };
        }) : {
            name: elem.name,
            value: val.replace(rCRLF, "\r\n")
        };
    }).get();
}
2
  • thanks for the effort, but check this fiddle: jsfiddle.net/cTKhH/13. The values of text box and radio buttons are not returned in the serialize output. Commented Apr 26, 2012 at 20:11
  • 1
    @jeffery_the_wind See updated post and the DEMO. Let me know if there are any issues. Good Luck! Commented Apr 26, 2012 at 20:26
2

A common solution to this problem is simply to include a hidden field with the same name as the checkbox, and the value "false"

This way, the submitted values will be either "false" if the checkbox is not checked, and "true,false" (assuming your checkbox has the value of "true") if it is checked.

Depending on your server-side code, then the "true, false" pair of values may get parsed as True, or it may need some help in parsing it. Some MVC frameworks will be happy with the true,false pair.

1

An alternative would be to use a jQuery plugin. For example, serializeJSON has the option to set the value for unchecked checkboxes like this:

$('form').serializeJSON({checkboxUncheckedValue: "false"});

In any case, it is usually best to use hidden inputs for unchecked values.

-2
<input type='hidden' name='check' value='false'/>
<input type='checkbox' name='check' value='true'/>

will output check = false if checkbox is unchecked.

3
  • Incase if checkbox is checked, it will return both checkbox value and the hidden value Commented Apr 26, 2012 at 19:49
  • You'll get a comma-separated value here if the checkbox is checked.
    – ScottE
    Commented Apr 26, 2012 at 20:14
  • the way to do it is to have a named hidden field with an id only check box and use java script to alter the hidden field onChange
    – Mr Heelis
    Commented Aug 15, 2017 at 13:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.