jQuery: serialize a form to JSON

by dhavaljani

HTML

<form action="#" method="post">
    <div>
        <label for="firstname">First Name</label>
        <input type="text" name="firstname" id="firstname" />
    </div>
    <div>
        <label for="lastname">Last Name</label>
        <input type="text" name="lastname" id="lastname" />
    </div>
    <div>
        <label for="age">Age</label>
        <input type="text" name="age" id="age" />
    </div>
    <div>
        <label for="email">Email</label>
        <input type="text" name="email" id="email" />
    </div>
    <div>
    <input type="checkbox" name="development" value="Splash Screen">Splash Screen<br>
    <input type="checkbox" name="development" value="Onboarding/help screens">Onboarding/help screens<br>
    <input type="checkbox" name="development" value="Empty states messaging and call to actions">Empty states messaging and "call to actions"<br>
    </div>
    <div>
        <label for="password">Password</label>
        <input type="password" name="password" id="password" />
    </div>
    <p>
        <input type="submit" value="Send" />
    </p>
</form>

CSS

form div {
    margin-bottom: 0.5em;
}
form div label, form div input {
    display: block;
    margin-bottom: 0.3em;
}

JavaScript

(function ($) {
    $.fn.serializeFormJSON = function () {

        var o = {};
        var a = this.serializeArray();
        $.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;
    };
})(jQuery);

$('form').submit(function (e) {
    e.preventDefault();
    var data = $(this).serializeFormJSON();
    console.log(data);

    /* Object
        email: "value"
        name: "value"
        password: "value"
     */
});