tags:

views:

25

answers:

1

How do I serialize dynamic form inputs?

<table id="mytable">
<form id="myform">
 <tbody>
   <tr><td><input type="text" name="row0"></td></tr> <!-- dynamically generated -->
   <tr><td><input type="text" name="row1"></td></tr> <!-- dynamically generated -->
   <tr><td><input type="text" name="row2"></td></tr> <!-- dynamically generated -->
   <tr><td><input type="text" name="row3"></td></tr> <!-- dynamically generated -->
 </tbody>
 <tfoot>
   <tr><td><input type="button" id="save" value="SAVE"></td></tr> <!-- static -->
 </tfoot>
</form>
</table>

I want to use jQuery to load info from php

$('#save').click(function(){
   $.ajax({
     type: "POST",
     url: "post.php",
     data: $('#myform').serialize(),
     success: function(msg){
         console.log(msg);
     }
   });
});

This would work no problem if the rows were not dynamically generated, but I can't figure out how to access or serialize the dynamic content.

+1  A: 

Serializing dynamic contents works fine the way you have it (since you're doing it in a click handler, not on load)...but you need to have a valid <form> element, where you have is isn't valid.

Instead wrap it around the <table>, like this:

<form id="myform">
<table id="mytable">
 <tbody>
   <tr><td><input type="text" name="row0"></td></tr> <!-- dynamically generated -->
   <tr><td><input type="text" name="row1"></td></tr> <!-- dynamically generated -->
   <tr><td><input type="text" name="row2"></td></tr> <!-- dynamically generated -->
   <tr><td><input type="text" name="row3"></td></tr> <!-- dynamically generated -->
 </tbody>
 <tfoot>
   <tr><td><input type="button" id="save" value="SAVE"></td></tr> <!-- static -->
 </tfoot>
</table>
</form>

You can test it out here.

Nick Craver
It was picking it up when it wasn't dynamically generated. I wonder why it has problems when it's dynamic.
polyhedron
That fixed it though.
polyhedron
@polyhedron - With invalid markup things are unporedictable...it may have placed the form differently in the DOM with the elements inside before.
Nick Craver
@polyhedron: if that solved your problem, you should mark it as the accepted answer so that others who have this problem can easily see the solution.
Ian Henry
it won't let me yet.
polyhedron