Serialize form data

Covert a form and its values to a JSON object

by santhosh lanka

HTML

<h2>Form</h2>
<div action="" method="post" class="for1">
First Name:<input type="text" name="Fname" maxlength="12" size="12"/> <br/>
Last Name:<input type="text" name="Lname" maxlength="36" size="12"/> <br/>
<p><input type="submit" /></p>
</div>
<h2>JSON</h2>
<pre id="result">
</pre>

CSS

form {
    line-height: 2em;
}
p {
    margin: 5px 0;
}
h2 {
    margin: 10px 0;
    font-size: 1.2em;
    font-weight: bold
}
#result {
    margin: 10px;
    background: #eee;
    padding: 10px;
    height: 40px;
    overflow: auto;
}

JavaScript

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            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;
};

$(function() {
    $('.for1').submit(function() {
        $('#result').text(JSON.stringify($('form').serializeObject()));
        return false;
    });
});