42

I haven't found a concrete answer as to whether this is possible, but it seems like it should be...

I would like to serialize all the input elements contained in a div. I can't use a form, because it would be nested within another form. I would then get the values and post them via ajax.

Here is the jsFiddle example I am playing with:

http://jsfiddle.net/9uyz5/

If I change the root to a it works as expected.

Thanks for your help.

I've modified the jsfiddle from this other question:

https://stackoverflow.com/a/1186309/25020

Community
  • 1
  • 1
B Z
  • 9,363
  • 16
  • 67
  • 91
  • I've written a blog response to your question. Here's how to serialize dom elements. I've also covered the possibility of creating a JSON string to be inserted in the database: http://onwebdev.blogspot.com/2012/03/jquery-serialize-elements-outside-forms.html – Gabriele Romanato Mar 06 '12 at 18:55
  • Possible duplicate of [jquery to serialize only elements within a div](http://stackoverflow.com/questions/1829519/jquery-to-serialize-only-elements-within-a-div) – showdev Aug 24 '16 at 19:17

4 Answers4

65

you need to serialize all the inputs inside your container, not the actual container itself. so:

$('div :input').serialize()
Omer Bokhari
  • 57,458
  • 12
  • 44
  • 58
  • 1
    out of curiosity, I find this is somewhat unexpected, why does $('#myForm').serialize() work? – B Z Mar 06 '12 at 18:43
  • 4
    A bit late I know but, `$('#myForm').serialize()` works because it is designed to serialize all elements in a form **or** a jQuery array of input elements. [As stated in the docs](http://api.jquery.com/serialize/) – Liam Oct 29 '13 at 17:14
10

Try this, to get all.

$('#divID *').serialize()
tiru
  • 789
  • 5
  • 20
  • 42
7

this also works with

$('div :input').serializeArray()

:)

Guntram
  • 961
  • 14
  • 19
4

For serializing the contents of the div with a button, this will be the more efficient way as it doesn't traverse through the entire dom.

$(this).closest('div').find("input,select,textarea").serialize();

make sure to attach this with the button event and make sure to include event.preventdefault with the button so that it does not submit the primary form if the div is inside it.

Arsen Khachaturyan
  • 7,904
  • 4
  • 42
  • 42