CONVERT FORM DATA TO JS OBJECT WITH JQUERY

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
JSON 
 1048  View(s)
Ratings:
Rate this:
Hi Developers,

How do I convert all elements of my form to a JS object?

I'd like to have some way of automatically building a JS object from my form, without having to loop over each element. I do not want a string, as returned by 

$('#formid').serialize();, nor do I want the map returned by $('#formid').serializeArray();

Thanks in advance! 
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: Convert form data to JS object with jQuery

    Hi Ankita,


    serializeArray already does exactly that, you just need to massage the data into your required format:

    Try as following

    $.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;
    };

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!