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?
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.
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