Reputation: 4597
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?
Upvotes: 4
Views: 10631
Reputation: 33865
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.
Upvotes: 11
Reputation: 4597
fixed by
function serializeAllFormData() {
var serializedData;
var forms = $('#content').find('form');
$(forms).each(
function() {
serializedData = serializedData
+ $(this).serialize();
});
alert(serializedData);
return serializedData;
}
Upvotes: 0