Quantcast
Viewing latest article 3
Browse Latest Browse All 4

jQuery Plugin: .serializeObject()

More often than not, you want an object of your form data to send to the server. I use cakePHP, which makes heavy use of input names like data[ModelName][attribute]. I needed a way to get that same nested format into an object I could send to the server in an $.ajax call so I made one.

$.fn.serializeObject works on any level of nested array syntax in your element names and creates arrays if items end in [], just like you’d expect.

For more information and source, check out my github repo.

For a demo, check out: http://jsfiddle.net/danheberden/3xcTG/

Example document:

<div id="test">
    <input name="text1" value="txt-one" />
    <input type="checkbox"
                name="top[child][]" value="1" checked="checked" />
    <input type="checkbox"
                name="top[child][]" value="2" checked="checked" />
    <input type="checkbox"
                name="top[child][]" value="3" checked="checked" />

    <select name="another[select]">
        <option value="opt"></option>
    </select>
</div>

Running $( '#test' ).serializeObject() returns:

{
  text1: "txt-one",
  top: {
    child: [ "1", "2", "3" ]
  },
  another: {
    select: "opt"
  }
}

Viewing latest article 3
Browse Latest Browse All 4

Trending Articles