1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
(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" */ }); |
or another approach
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function jQFormSerializeArrToJson(formid) { var serializedArr = $("form#" + formid).serializeArray(); var jsonObj = {}; jQuery.map(formSerializeArr, function(n, i) { jsonObj[n.name] = n.value; }); return jsonObj; } $('#formidlogin').submit(function(e) { e.preventDefault(); var data = jQFormSerializeArrToJson('formidlogin'); data = JSON.stringify(data), console.log(data); /* Object email: "value" name: "value" password: "value" */ }); |