views:

28

answers:

2

So, somewhat standard situation:

OK, so replacing <div> with <form> works. Now to see if any nesting issues occur...

<div id=hidden>
     <input type=hidden value=2 id=i1 name=i1>
     <input type=hidden value=5 id=i2 name=i2>
     <input type=hidden value=6 id=i3 name=i3>
     <input type=hidden value=1 id=i4 name=i4>
     <input type=hidden value=10 id=i5 name=i5>
</div>

I need to submit this data via POST. however alert ($('#hidden').serialize()); returns blank string. What have I done wrong?

+4  A: 

Due to it's used of .elements, you can only .serialize() a <form> so change your <div> to a <form> and it'll work.

For illustration, here's the <div> version (not working) and the <form> version (working).

As an aside, make sure to enclose your attributes in quotes, like this:

<form id="hidden">
  <input type="hidden" value="2" id="i1" name="i1">
  <input type="hidden" value="5" id="i2" name="i2">
  <input type="hidden" value="6" id="i3" name="i3">
  <input type="hidden" value="1" id="i4" name="i4">
  <input type="hidden" value="10" id="i5" name="i5">
</form>​

An alternative is to break .serialize() down into its parts, like this:

alert($.param($('#hidden :input').serializeArray()));
//or
alert($('#hidden :input').serialize());

Check out that version here (note it works with <div>).

Nick Craver
+1  A: 

try

alert($('#hidden input').serialize()); ​// this will serialize all input element.

if you want to Selects all input, textarea, select and button elements, use :input

from the Docs,

The .serialize() method can act on a jQuery object that has selected individual form elements, such as <input>, <textarea>, and <select>. However, it is typically easier to select the <form> tag itself for serialization

crazy demo

Reigel
Did you mean to link to my exact fiddle, or make you own? :)
Nick Craver
hahaha wrong copy pasting ;) thanks!
Reigel