jQuery Plugin: .serializeForm()

Published on: 08:04, 01-04-2011 Filed Under: Uncategorized View Comments

[Update: 2013-03-23. Renamed serializeObject to serializeForm]

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.serializeForm 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' ).serializeForm() returns:

{
  text1: "txt-one",
  top: {
    child: [ "1", "2", "3" ]
  },
  another: {
    select: "opt"
  }
}
  • http://kflorence.com Kyle Florence
  • Anonymous

    I didn’t want to have to call serializeArray and decompose its output into a new object :) and the logic can be applied outside of jquery if someone so desired so I felt it a worthwhile contribution.

  • http://www.facebook.com/asadg Asad Hasan

    Thank you so much for this epic plugin…makes my drupal webforms submit seamlessly within a JQuery Dialog without having to use an iframe

  • http://jmack.parhelic.com/ jm9000

    This function really should be part of jQuery core.

  • Ryan

    Heya, so I’ve been using this but realized it isn’t serializing checkboxes that are NOT checked. Is there a way to tell it to do this?

  • http://twitter.com/klederson klederson

    Very well done, great script and works perfectly fine =)

  • 44

    44

  • Otacon Overdrive

    Thanks for this great plugin, Ben’s cannot handle multi-dimensionals..

  • Rabeesh Kumar

    Ben covert mutilform like

    {
    “general[url]“:”",
    “general[description]“:”",
    “is_approved”:”1″
    }

    but dam converts correct form

    {
    “general”:{
    “url”:”",
    “description”:”"
    },
    “is_approved”:”1″
    }

    Nice work dan !

  • Rabeesh Kumar

    For a array , index start with 0 to n .. it convert into {“general”:{“url”:”http://local/test/one.jpg”,”description”:”Helllo”,”show_profile”:false},”education”:{“0″:{“title”:”a”,”description”:”b”},”1″:{“title”:”c”,”description”:”d”},”length”:2}}

    it will be great .. if education act like an array

blog comments powered by Disqus