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.
To serialize a FormData object into a query string, pass it into the new URLSearchParams() constructor. This will create a URLSearchParams object of encoded query string values. Then, call the URLSearchParams. toString() method on it to convert it into a query string.
The serialize() method creates a URL encoded text string by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself. The serialized values can be used in the URL query string when making an AJAX request.
What will you use in jQuery if you wanted to convert the contents of a form element into string for submission? You can do this: var frm = $(document. myform); var data = JSON. stringify(frm.
In JavaScript, for example, you can serialize an object to a JSON string by calling the function JSON. stringify() . CSS values are serialized by calling the function CSSStyleDeclaration. getPropertyValue() .
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 wrapped 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With