HTML checkbox as boolean values with jQuery (using ASP.NET MVC Web-Api)

I like to have my HTML form data to be send in JSON. When reading values from checkboxes with the default jQuery serializeArray you get the value “on” for checkboxes that are checked. In my viewmodel I have boolean properties so they won’t be validated.

Searching on the internet I found various ways to accomplish it. I didn’t want to use yet another library so I wanted a nice jQuery solution.

I combined two solutions that perfectly suited my situation, the result is this little composite jQuery plugin:

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray({ checkboxesAsBools: true});
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });

    return o;
};

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

    var rselectTextarea = /select|textarea/i;
    var rinput = /text|hidden|password|search/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') ? //moar ternaries!
                    (this.checked ? 'true' : 'false') :
                    val
            };
        }).get();
};

Now when I want to send data to my server all I need to supply jQuery is this data:

var data = JSON.stringify($("#myForm").serializeObject();

//TODO make an AJAX call

Note: JSON.stringify is available in modern browsers, use an library if you want to support older browsers. It converts a Javascript object to a string.

Sources that is used:
http://tdanemar.wordpress.com/2010/08/24/jquery-serialize-method-and-checkboxes/

http://css-tricks.com/snippets/jquery/serialize-form-to-json/

Advertisements
This entry was posted in ASP.NET, HTML, JavaScript, jQuery, JSON, MVC, Web-Api and tagged , , , , , , , , . Bookmark the permalink.

6 Responses to HTML checkbox as boolean values with jQuery (using ASP.NET MVC Web-Api)

  1. Great contribution. Thanks for sharing! Check your ampersands — looks like they got encoded on post.

  2. Thanks !
    Unfortunately, boolean are not correctly parsed as boolean value. Thus I just change on line 47, ‘true’ by true (no quote) and same for false.

    Thanks for sharing.

    • rburgundy says:

      I guess that depends on the server side software that seralizes/parses your request. In my situation the stringed boolean values are sufficient. I’m using MVC4 ASP.NET.

  3. Perfect, had to deal with “on” in json and other bogus stuff, you saved me, thank you!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s