Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing a subset of form

I have a form that embeds another form:

<form>
  <input type="text" name="main[name]">
  <textarea name="main[body]"></textarea>
  <div id="embedded">
    <input type="text" name="main[embedded][name]">
    <textarea name="main[embedded][body]"></textarea>
  </div>
</form>

I need to serialize the embedded form only.

$('#embedded').serialize() results in empty string.

like image 556
Dziamid Avatar asked Dec 13 '11 10:12

Dziamid


People also ask

How do you serialize form data?

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.

What is meant by serialization?

Serialization is the process of converting a data object—a combination of code and data represented within a region of data storage—into a series of bytes that saves the state of the object in an easily transmittable form.

What does serialize method do?

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.


2 Answers

You are not embedding another form, you are embedding a div.

The serialize() method can only be called on a form elements, or the form element itself.

var serialized = $('#embedded').find(':input').serialize();

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:

like image 147
Matt Avatar answered Sep 21 '22 12:09

Matt


I haven't tested this, but you could try:

$("<form/>").html($('#embedded').clone()).serialize()
like image 45
paulslater19 Avatar answered Sep 22 '22 12:09

paulslater19