jQuery $('form').serialize() returns only one element of a form serialized

7.4k views Asked by At

Given the following form:

<form id="form" name="form">
<input name="name"/>
<input name="version"/>
<input name="template"/>
<textarea name="elements"></textarea>
<textarea name="features"></textarea>
<textarea name="layout"></textarea>
<input type="submit" value="Save"/>
</form>

and javascript (using jQuery 1.3.2):

$(function() {
    $('#form').bind('submit',function() { alert($('#form').serialize()); return false; });
    });

The output of submitting the above form from the above javascript alert is:

elements=...

Where ... is whatever is contained in the elements field.

I would expect that $('#form').serialize() to return a string something like:

name=&version=&template=&elements=&features=&layout=.

I do note that $('input,textarea').serialize() does perform the expected behaviour (i.e. return "name=&version=&template=&elements=asdafe&features=&layout="), however I'm curious as to why the $('#form') version only returns "elements=".

I've tried this on Safari 4 and Firefox 3.5, so I'm confident it's something I'm missing.

Thanks for reading.

3

There are 3 answers

1
Peter Bailey On BEST ANSWER

It's the name of your textarea that's throwing it off.

Here's how it breaks down. In the DOM, form nodes have several special properties, most notably these two (which are exposed in this order)

  1. The elements collections, which is an HTMLCollection of all the form controls (and a few other nodes like <fieldset> elements)
  2. A property of each named element in the form (i.e., form controls that have a name attribute)

Since you have a <textarea> with the name "elements", this effectively overwrites the built-in elements collection mentioned in #1 above, which is why when you serialize the form all you see is

elements=****

Because that single form element has overwritten the entire collection.

Short solution? re-name your form elements to values that aren't existing DOM properties (your <input name="name"/> falls into this category as well)

0
Steven Benjamin On

The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. It operates on a jQuery object representing a set of form elements. The form elements can be of several types:

0
Max On

If anyone else stumbles on this problem, I had set the disabled property on all inputs before calling serialize(), so they weren't included in the set. Removing disabled before calling serialize() fixes this.