Convert HTML Form to JSON


Option -1:
function form_to_json(selector) {
    var ary = $(selector).serializeArray();
    var obj = {};
    for (var a = 0; a < ary.length; a++) obj[ary[a].name] = ary[a].value;
    return obj;
}

//Example
var mydata = form_to_json('#form');
JSON.stringify(mydata);
---------------------------------------------------------

Option-2:
Using Third party JQuery plugin- http://maxatwork.github.io/form2js/

<script src="form2js.js"></script>
<script src="jquery.toObject.js"></script>

var data = $('#form').toObject({skipEmpty:false});
JSON.stringify(data)
Advertisements

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