Ciel
Ciel

Reputation: 17752

json2 from multiple form fields, getting bad values in jQuery

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?

Upvotes: 1

Views: 1582

Answers (4)

Timothy
Timothy

Reputation: 4285

You can easily translate form data to a JSON string like this:

allFormTags = $(document.yourFormName).serializeArray();

var myjson = {}; 
$.each(allFormTags, function() {
    myjson[this.name] = this.value;
})

Upvotes: 0

Pointy
Pointy

Reputation: 413709

Well you could translate it yourself:

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

Upvotes: 0

Dimskiy
Dimskiy

Reputation: 5301

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.

Upvotes: 3

Harmen
Harmen

Reputation: 22438

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

Upvotes: 1

Related Questions