You can use the FormData
API in JavaScript. Here’s an example of how you can serialize form data:
function serializeFormData(form) {
var formData = new FormData(form);
var serializedData = {};
for (var [name, value] of formData) {
if (serializedData[name]) {
if (!Array.isArray(serializedData[name])) {
serializedData[name] = [serializedData[name]];
}
serializedData[name].push(value);
} else {
serializedData[name] = value;
}
}
return serializedData;
}
// Example usage
var myForm = document.getElementById('myForm');
var serializedForm = serializeFormData(myForm);
console.log(serializedForm);
In the code above, the serializeFormData
function takes a reference to a form element as a parameter. It creates a new instance of FormData
by passing the form element to it. Then, it iterates over the entries in the FormData
object using a for...of
loop.
For each entry, it checks if the name
already exists as a property in the serializedData
object. If it does, it converts the value to an array (if it’s not already) and pushes the new value. If it doesn’t exist, it sets the value directly.
Finally, it returns the serializedData
object, which contains the serialized form data.
You can use this serializeFormData
function to serialize form data without jQuery, just like in the example usage provided. Modify the code according to your specific HTML form structure and requirements.
