4

I have the following form ...

<form id="my-form">

  <fieldset name="address">
    <input name="streetAddress" type="text" placeholder="Street Address"><br>
    <input name="city"          type="text" placeholder="City"><p>,</p>
    <input name="state"         type="text" placeholder="State">
    <input name="zipCode"       type="text" placeholder="Zip Code">
  </fieldset>

  <fieldset name="dimensions">
    <input name="length" type="text" placeholder="length">
    <input name="width"  type="text" placeholder="width">
    <input name="height" type="text" placeholder="height">
  </fieldset>

</form>

I need to serialize it into JSON with JS, but I need to have the address's fields warped in an address object, and the dimensions's fields warped in a dimensions object.

Something like this ...

{
    'address':{'streetAddress':'111 Candy Ln', 'city':'Los Angeles', ...}, 
    'dimensions':{...}
}

How do you do this cleanly, idealy without having to write my own function for doing this? I have of course seen scripts to serialize, but nothing that will do embedded objects.

Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81
Marc M.
  • 3,631
  • 4
  • 32
  • 53

2 Answers2

2

Have you tried putting all the fields into arrays?

<fieldset name="address">
<input name="address[streetAddress]" type="text" placeholder="Street Address"><br>
<input name="address[city]" type="text" placeholder="City"><p>,</p>
<input name="address[state]" type="text" placeholder="State">
<input name="address[zipCode]" type="text" placeholder="Zip Code">
</fieldset>

Heres an example, using the serializeObject plugin

Just include that script and you can convert any form into a multi layered JSON object.

DEMO HERE

Using this plugin...more info here Convert form data to JavaScript object with jQuery

(function($){
$.fn.serializeObject = function(){

    var self = this,
        json = {},
        push_counters = {},
        patterns = {
            "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
            "key":      /[a-zA-Z0-9_]+|(?=\[\])/g,
            "push":     /^$/,
            "fixed":    /^\d+$/,
            "named":    /^[a-zA-Z0-9_]+$/
        };


    this.build = function(base, key, value){
        base[key] = value;
        return base;
    };

    this.push_counter = function(key){
        if(push_counters[key] === undefined){
            push_counters[key] = 0;
        }
        return push_counters[key]++;
    };

    $.each($(this).serializeArray(), function(){

        // skip invalid keys
        if(!patterns.validate.test(this.name)){
            return;
        }

        var k,
            keys = this.name.match(patterns.key),
            merge = this.value,
            reverse_key = this.name;

        while((k = keys.pop()) !== undefined){

            // adjust reverse_key
            reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');

            // push
            if(k.match(patterns.push)){
                merge = self.build([], self.push_counter(reverse_key), merge);
            }

            // fixed
            else if(k.match(patterns.fixed)){
                merge = self.build([], k, merge);
            }

            // named
            else if(k.match(patterns.named)){
                merge = self.build({}, k, merge);
            }
        }

        json = $.extend(true, json, merge);
    });

    return json;
};
})(jQuery);
Community
  • 1
  • 1
Kylie
  • 11,421
  • 11
  • 47
  • 78
1

I have two solutions for this:

  1. Name the fields after the fieldsets (like the proposal above): address[street], address[zipcode], etc.
  2. Give the fieldsets some unique id's.

In both cases I suggest you using this library I made: https://github.com/serbanghita/formToObject

Call it like this:

Case 1: var myFormObj = new formToObject('myFormId');

Case 2: var myFormObj = new formToObject('myFieldsetId');

Șerban Ghiță
  • 1,899
  • 20
  • 21