illithoid
illithoid

Reputation: 25

Using serializeObject() on a form to create a JSON object with an inner array

I have a form looks a little like this

<form>
<input type='text' name='_id'/>
<input type='text' name='name'/>
<textarea name='description'/>
<input type='text' name='category'/>
<input type='checkbox' name='reservable'/>
<ol>
    <li><input type ='text' name='_id'/><input type='text' name='name'/><input type='text' name='value'/></li>
    <li><input type ='text' name='_id'/><input type='text' name='name'/><input type='text' name='value'/></li>
</ol>
</form>

I'm trying to use the serializeObject() method on this form and it's working well for the most part. Problem is I want the elements inside the list to be made into an array with each li element an object in the array like so..

{
_id:'5',
name:'bob',
description:'tall',
categoryId:'human',
reservable:'false',
attributes:
[
    {
        _id:'3',
        name:'hair',
        value:'brown'
    }
]

}

What I'm getting now looks like this

 {
 "_id:":"5",
 "name:":"bob",
 "description:":"tall",
 "categoryId":"human",
 "name":["hair",""],
 "value":["brown",""]
 }

Is there a way I can get it to make attributes an array of objects? Also if somebody could tell me why my checkbox isn't showing up I'd greatly appreciate it.

Upvotes: 1

Views: 697

Answers (1)

Josh Wa
Josh Wa

Reputation: 1049

I am doing this without testing, so hopefully I don't fail and can push you in the right direction. I would try something similar to this:

HTML

<form>
<input type='text' name='_id' id="the_id"/>
<input type='text' name='name' id="the_name"/>
<textarea name='description' id="desc"/>
<input type='text' name='category id='category'/>
<input type='checkbox' name='reservable' id='reservable' />
<ol>
    <li><input type ='text' name='_id'/><input type='text' name='name' id='attr_part' /><input type='text' name='value'/></li>
    <li><input type ='text' name='_id'/><input type='text' name='name id='attr_color'/><input type='text' name='value'/></li>
</ol>
</form>

jQuery

// Initializes the array
var person = {};

person.id = $('#the_id').val();
person.name = $('#the_name').val();
person.desc = $('#desc').text();
person.category = $('#category').val();
person.reservable = $('#reservable').val();

// Initialize the attributes array
person.attributes = {};

var attribute = {};

attribute.part = $('#attr_part').val();
attribute.color = $('#attr_color').val();

person.attributes.push(attribute);

Upvotes: 2

Related Questions