Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 815
Brian M. Hunt Avatar asked Aug 17 '09 19:08

Brian M. Hunt


2 Answers

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)

like image 140
Peter Bailey Avatar answered Sep 25 '22 00:09

Peter Bailey


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.

like image 40
Max Avatar answered Sep 27 '22 00:09

Max