Adrian Enache
Adrian Enache

Reputation: 93

jQuery/javascript get form data just like a post array

I have an HTML form and I want to get all its data in the same structure as a $_POST would. So if I have some inputs like this:

<input type="text" name=r[1][0] value="x"><input type="text" name=r[1][1] value="y">

I would like to get and object like this:

obj = {r:{1:{0:x,1:y}}}

Can you please tell me there is any way I could do this? I tried serializeArray().. and other "custom" solutions with no success.

Thank you! :)

Upvotes: 0

Views: 140

Answers (1)

Jax Teller
Jax Teller

Reputation: 1467

1 weeks ago, i had almost same problem, i developed a function which can convert input to a JavaScript object.

It's maybe more then what you need, but you can take a look in this :

    var myObj = {};

    function addValueToObj(objet, nom) {

                var pathBrackets = "";
                var regex = /\[([0-9]+)\]$/;
                nom = nom.split("=");
                var path = nom[0].split('.');

                val = nom.slice(1).join("=");

    for (var i = 0, tmp = objet; i<path.length-1; i++) {
                    pathBrackets += path[i]+".";    
                    if (path[i].match(regex)!=null) {

                        var valindex = path[i].match(regex)[1];
                        var index = path[i].match(regex).index;
                        var newPath = path[i].substring(index, 1-path[i].length);

                        if (typeof tmp[newPath] == "undefined") {
                            tmp = tmp[newPath] = [];
                            tmp = tmp[valindex] = {};
                        } else {
                            if (typeof tmp[newPath][valindex] == "undefined") {
                                tmp = tmp[newPath][valindex] = {};
                            } else {
                                tmp = tmp[newPath][valindex];
                            }
                        }
                    } else {
                        if (typeof tmp[path[i]] == "undefined") {
                            tmp = tmp[path[i]] = {};
                        } else {
                            tmp = tmp[path[i]];
                        }


        }

            }

        tmp[path[i]] = val;
}

$(document).ready(function() {
  $.each($("input"), function() {
        addValueToObj(myObj, $(this).attr('name')+"="+$(this).val());
  })
  console.log(myObj);
})

and the HTML :

<form>
x :<input type="text" name="r.1.0" value="x">
y :<input type="text" name="r.1.1" value="y">
</form>

Result :

{
"r":{
  "1":{
    "0":"x",
    "1":"y"
   }
  }
}

Hope it can help you.

Here the JSFiddle

Upvotes: 2

Related Questions