Categories: Snippets

Serialize Form to JSON

(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

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"
  */});

 

Share
Tags: formjson

Recent Posts

Selecting Elements in jQuery (jQuery Selectors)

To collect a group of elements, we pass the selector to the jQuery function using…

5 years ago

jQuery library Introduction

jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is…

5 years ago

Adjust li width fit with ul width of the outer div/body

HTML:- [crayon-6636a00ca1bce176831822/] CSS:- [crayon-6636a00ca1bd4977184074/] JavaScript:- [crayon-6636a00ca1bd6065915629/]  

5 years ago

Customize Input Box using jQuery

Prevent users typing special characters in text box, textarea, etc. [crayon-6636a00ca1d4c171879937/] ^[a-zA-Z]+$ Alphabets ^[a-zA-Z\s]+$ Alphabets…

5 years ago

JavaScript simple form validation with example

Any interactive web site has form input - a place where the users input different…

5 years ago

Clear the browser cache of CSS or JavaScript Using Javascript

[crayon-6636a00ca2061869341299/]  

5 years ago