tags:

views:

24

answers:

3

I have a setup with multiple form fields..

<input type='text' id='Trait1' >0</input>
<input type='text' id='Trait2' >1</input>
<input type='text' id='Trait3' >2</input>
<input type='text' id='Trait4' >3</input>

(data used is just for example)

When I use

$.JSON.Stringify(form.serializeArray());

I get something like..

[{'name','Trait1','value','0'}]

etc.

This doesn't translate well, because everything trying to deserialize it from json sees the 'name' and 'value' as the actual objects (where 'trait1' and '0' are the actual objects).

Is there anything I can do?

A: 

<input type='text' id='Trait1' >0</input> is incorrect use of the input element. Try <input type='text' id='Trait1' value='0'/>

Harmen
+1  A: 

Take a look at this blog post:

http://www.foreachbit.com/2010_09_01_archive.html

or in short, you could use something like this to get rid of names and values:

  var formVals = $('#MyForm').serializeArray();
  var jsonObj = {};

  for (i in formVals)
    jsonObj[formVals[i].name] = formVals[i].value;

  var submitVals = $.toJSON({ "MyFormData": jsonObj });

Where $.toJSON is the Stringify methode.

Oh, and Harman is absolutely right. Use the value attribute in your inputs.

Dimskiy
It's pretty dangerous to use `for ... in` to iterate over arrays.
Pointy
In the example above, there are only 3 elements. But sure, to be safe, you could always check the .length property of formVals
Dimskiy
You don't know what the array might have inherited from a manipulated Array.prototype object. Using `for ... in` on simple arrays is generally considered a Bad Idea by the Javascript know-it-alls.
Pointy
The array got its data as a result of jQuery's serializeArray() function. I see the point you're making, but then should I also not consider using serializeArray() at all?
Dimskiy
No, no. Here's the deal: the `for ... in` construct is for iterating over properties of an object. An Array instance is a *specialized* object, and to iterate over just the indexed elements of the array, you should always use `for (var i = 0; i < a.length; i++)` loop. That avoids any possibility of running into unexpected attributes on the object.
Pointy
Interesting. Thanks for the info, Pointy. I'll do some more reading on this.
Dimskiy
A: 

Well you could translate it yourself:

$.JSON.Stringify($.each(form.serializeArray(), function(inp) {
  var rv = {}; rv[inp.name] = inp.value; return rv;
}));
Pointy