-1

I have a form with several textboxes. I want to serialize the whole form to json in a way that those text boxes remains in an array. I have the following html

<form id ="myform">
    <input type="text" name="options[]"/>
    <input type="text" name="options[]"/>
    <input type="text" name="options[]"/>
    <input type="text" name="options[]"/>
</form>

And I use jquery to convert it to json

JSON.stringify($("#myform").serializeArray());

This gives me the following:

  {
    "options[]":"Content of the last textbox"
  }

but I want

  {
   "options":
             {
              "0":"value",
              "1":"value",
              "2":"value",
              "3":"value",
             }
  }

How can I achieve this using javascript?

DalekSupreme
  • 1,493
  • 3
  • 19
  • 32
  • 2
    Actually, it doesn't give you that all-> **http://jsfiddle.net/adeneo/knnsb0vt/** , it gives you an array in the proper format for an ajax request in form-www-urlencoded. – adeneo Apr 20 '15 at 16:18
  • 2
    "Content of the last checkbox"? But you're using text fields. – Blazemonger Apr 20 '15 at 16:19
  • `serializeArray` won't help with this. You have to build that json manually – hindmost Apr 20 '15 at 16:21
  • possible duplicate of [Convert form data to JS object with jQuery](http://stackoverflow.com/questions/1184624/convert-form-data-to-js-object-with-jquery) – Liam Apr 20 '15 at 16:21
  • I have updated my answer which I hope is a better solution now to your question – AmmarCSE Apr 20 '15 at 16:33

4 Answers4

1
var arr = $("#myform").serializeArray();
var result = {"objects":{}};
arr.forEach(function (elem, i) {
    result.objects[i] = elem["value"];
});

console.log(JSON.stringify(result));

Here is a fiddle

marcel
  • 2,967
  • 1
  • 16
  • 25
0

This can be done manually with jQuery serializeArray() as an aid

var serializedArray = $('#myform').serializeArray();
var customArray = {};
customArray['options'] = {};
for(key in serializedArray)
{
    customArray['options'][key] = serializedArray[key]['value'];
}

fiddle

AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • Are you suggesting `serializeArray` doesn't handle names with `[]` ? The two methods should be the same, but one returns a querystring, the other an array ? – adeneo Apr 20 '15 at 16:21
  • I don't think this is a good answer. It doesn't really solve the question at all – Liam Apr 20 '15 at 16:22
  • @adeneo, you are right, I have updated my answer. Thanks for the tip. – AmmarCSE Apr 20 '15 at 16:32
0

try This

<script type="text/javascript">
    $(document).ready(function(){

        $("#myform").submit(function(event){
            var foo=$(this).serializeArray();
            var option={"option":foo};

            console.log(JSON.stringify(option));
            return false;
        });


    });


      </script>
Buddhika
  • 13
  • 10
0

So i came across this question after I solved the same problem my self. I searched everywhere for a solution and it feels like i'm missing something basic (either javascript/jquery or .net MVC) that would do this for me. But this is how I eventually managed to solve a similar problem to yours.

    var serializeForm = function (form) {
        var result = [];
        var buildArray = function m(name, value) {
            var match = name.match(/\[\d+\]/);
            if (!match) {
                var ret = {};
                ret[name] = value;
    
                return ret;
            } else {
                var ret = {};
                var thisName = name.slice(0, match.index);
                var index = match[0].match(/\d+/)[0];
    
                ret[thisName] = m(name.slice(match.index + match[0].length + 1), value);
                ret.index = index;
                return ret;
            }
        };
    
        $.each(form, function (i, o) {
            result.push(buildArray(o.name, o.value));
        });
    
        var json = {};
        var buildObject = function m(json, o) {
            var indexKey = 'index';
            for (var key in o) {
                if (key != indexKey) {
                    if (o.hasOwnProperty(indexKey)) {
                        if (!json.hasOwnProperty(key)) {
                            json[key] = [];
                        }
    
                        if (!json[key].hasOwnProperty(o[indexKey])) {
                            json[key][o[indexKey]] = {};
                        }
    
                        json[key][o[indexKey]] = m(json[key][o[indexKey]], o[key]);
                    } else {
                        json[key] = o[key];
                    }
                }
            }
            return json;
        }
        $.each(result, function (i, o) {
            buildObject(json, o);
        });
        return json;
    }
    
    $(function(){
      console.log(serializeForm($('form').serializeArray()));
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input name="low[0].mid[0].high" value="0 0" type="text" />
  <input name="low[0].mid[1].high" value="0 1" type="text" />
  <input name="low[1].mid[0].high" value="1 0" type="text" />
  <input name="low[1].mid[1].high" value="1 1" type="text" />
</form>
  • I realize it only partially answers your question. And my problem was different than yours. But maybe you can modify it to solve yours? – Hydrospanners Mar 10 '16 at 15:18