Learn how to change the default behaviour of setting the checkboxes value as On and Off during the serialization of a form with jQuery Serialize and Serialize Array.

During the serialization of Data that will be sent to your server with AJAX, you will face a serious behaviour that can affect considerably the quantity of code that you write and the style as well. We usually send the information from a form, for example the following one:

<form id="myForm" action="cheese.php" method="post">
    <label>Name</label>
    <input type="text" name="name">
    <br>

    <label for="isProgrammer">Programmer</label>
    <input type="checkbox" name="isProgrammer" id="isProgrammer">
    <br>
    <label for="isDesigner">Designer</label>
    <input type="checkbox" name="isDesigner" id="isDesigner">

    <br>
    <label>Male</label>
    <input type="radio" name="gender" value="male">
    <label>Female</label>
    <input type="radio" name="gender" value="female">

    <br>
    <label>Description</label>
    <textarea name="description" cols="30" rows="10"></textarea>
</form>

<input type="button" id="btn" value="Serialize"/>

<script>
    $("#serialize").on("click", function(){
        var data = $("#myForm").serialize();
        alert(data);
    });

    $("#serializeArray").on("click", function(){
        var data = $("#myForm").serializeArray();
        alert(JSON.stringify(data));
    });
</script>

This can be easily done with jQuery easily using the serialize or serializeArray methods as shown in the script tag when the user clicks respectively on every button:

Serialize and SerializeArray Form jQuery

which would generate respectively the following output:

name=Carlos&isProgrammer=on&gender=male&description=This%20is%20me.

And with serializeArray:

[
   {
      "name":"name",
      "value":"Carlos"
   },
   {
      "name":"isProgrammer",
      "value":"on"
   },
   {
      "name":"gender",
      "value":"male"
   },
   {
      "name":"description",
      "value":"This is me."
   }
]

This makes the things easier for you as it doesn't include the data from empty inputs and you don't need to write extra code. The problematic comes up with the famous checkbox input, whose serialization sets as value when it's checked a string value namely "on". This happens, because a checked checkbox simply sends its value attribute, however as we don't have any value attribute defined in the checkbox, the sent value when it's checked its a simple "on" text. As you may know, an unchecked checkbox doesn't send itself in the form, so the browser determines if it was checked or not and sets its value to "on".

However for some developers, it may result easier to manipulate directly the sent data from jQuery when its serialized by jQuery.serializeArray with a JSON string that gets automatically converted into an array of PHP/or favorite server language to work with. But this value "on" isn't helpful at all when we work with booleans. Instead, we would like to retrieve a true value.

1. Include jQuery extension

The first step to accomplish our needs, is to add the following jQuery extension of serialize and serializeArray in your project:

/**
 * Slightly modified the original script from this website. Instead of setting true and false as strings
 * it should send a plain Boolean variable.
 * 
 * @see https://tdanemar.wordpress.com/2010/08/24/jquery-serialize-method-and-checkboxes/
 */
(function ($) {
    $.fn.serialize = function (options) {
        return $.param(this.serializeArray(options));
    };

    $.fn.serializeArray = function (options) {
        var o = $.extend({
            checkboxesAsBools: false
        }, options || {});

        var rselectTextarea = /select|textarea/i;
        var rinput = /text|hidden|password|search|number/i;

        return this.map(function () {
            return this.elements ? $.makeArray(this.elements) : this;
        })
        .filter(function () {
            return this.name && !this.disabled &&
                (this.checked
                || (o.checkboxesAsBools && this.type === 'checkbox')
                || rselectTextarea.test(this.nodeName)
                || rinput.test(this.type));
            })
            .map(function (i, elem) {
                var val = $(this).val();
                return val == null ?
                null :
                $.isArray(val) ?
                $.map(val, function (val, i) {
                    return { name: elem.name, value: val };
                }) :
                {
                    name: elem.name,
                    value: (o.checkboxesAsBools && this.type === 'checkbox') ?
                        (this.checked ? true : false) :
                        val
                };
            }).get();
    };
})(jQuery);

This extension will not modify the default behaviour of jQuery.serialize and jQuery.serializeArray. It just provides a new option, namely checkboxesAsBools, so when this option is defined and set to true, it will run the logic of the extension.

2. Checkboxes as Booleans

To define the behaviour of serializing checkboxes as Booleans, you will need to specify the new option of this method:

var data = $("#myForm").serialize({
    checkboxesAsBools: true
});

console.log(data);

// name=Car&isProgrammer=true&isDesigner=false&gender=male&description=qweqwe

Or with serializeArray:

var data = $("#myForm").serializeArray({
    checkboxesAsBools: true
});

console.log(data);

/*
[
   {
      "name":"name",
      "value":"Car"
   },
   {
      "name":"isProgrammer",
      "value":true
   },
   {
      "name":"isDesigner",
      "value":false
   },
   {
      "name":"gender",
      "value":"male"
   },
   {
      "name":"description",
      "value":"qweqwe"
   }
]
*/

The advantage of this approach is exactly the fact that the default behaviour of the methods isn't compromised. You will need to specify when the checkboxes should be handled as booleans in the serialization.

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors