Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all forms in the page and serialize their input values

Hello i am trying to Select all forms in the page and then serialize their input values, i am using the following code:

function serializeAllFormData() {
                        var serializedData;
                        $("#form").each(
                                function() {
                                    serializedData = serializedData
                                            + $(this).serialize();
                                });
                        return serializedData;
                    }

but when i inspect serializedData it is undefined, what i am doing wrong?

like image 316
skystar7 Avatar asked Dec 21 '22 18:12

skystar7


1 Answers

You are selecting the forms as if they were an ID #form (the hash sign # is only used when selecting on an ID). Try using just form instead.

$("form").each(function() {
   serializedData = serializedData + $(this).serialize();
});

Update

According to the documentation the each function can take a first argument (indexInArray). So you could do something like this:

var forms = $("form");
forms.each(function(i) {
   serializedData = serializedData + $(this).serialize();

   // i will start a 0, therefor forms.length - 1 in the if-statement
   if (i === forms.length - 1) {
      // Do something on the last element
   }
});

I cache the forms in a variable so that we don't have to go through the DOM every time the loop runs.

like image 67
Christofer Eliasson Avatar answered Feb 20 '23 09:02

Christofer Eliasson