1

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.

1
  • Unchecked checkboxes have no value, hence will never show up. You could take your existing result and map/reduce it to the result you expect, filling in the defaults for any missing values. Commented May 6, 2013 at 3:32

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.