how to make unchecked check box return a value with jQuery serialize?

12,127

Solution 1

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());
    });
});

Solution 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.

Solution 3

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();
}

Solution 4

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.

Share:
12,127
jeffery_the_wind
Author by

jeffery_the_wind

Currently a Doctoral student in the Dept. of Math and Stats at Université de Montréal. In the past I have done a lot of full stack development and applied math. Now trying to focus more on the pure math side of things and theory. Always get a lot of help from the Stack Exchange Community! Math interests include optimization and Algebra although in practice I do a lot of machine learning.

Updated on June 15, 2022

Comments

  • jeffery_the_wind
    jeffery_the_wind almost 2 years

    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.