For the past few weeks, I've been writing about a series of helper functions I wrote for serializing form data:
- Serialize form data into a query string in vanilla JS
- Serialize form data into an array in vanilla JS
- Serialize form data into an object in vanilla JS
- Serialize form data into a JSON string in vanilla JS
At the weekend, I encapsulated them into a tiny form serialization library called Serialize.js. The minified and gzipped file weighs less than 500 bytes! 😱
Let me show you how it works.
Include the script
The easiest way to get started is by using the jsDelivr CDN:
<script src="https://cdn.jsdelivr.net/npm/@kieranbarker/serialize@1/dist/serialize.min.js"></script>
You can also download the files directly from GitHub or use your favourite package manager. Check the documentation to learn more.
Instantiate the library
To create a new instance, just instantiate the class using the new
operator, passing in an HTMLFormElement
.
You can select the form any way you like, such as using the document.forms
property or the document.querySelector()
method:
// Using the document.forms property
const serialize = new Serialize(document.forms[0]);
// Using the document.querySelector() method
const serialize2 = new Serialize(document.querySelector('form'));
Use the instance methods
Once you've created an instance, you have four methods available to you: string()
, array()
, object()
, and json()
.
To use them in practice, you would probably do something like this:
document.forms[0].addEventListener('submit', function (event) {
// Prevent the default submission
event.preventDefault();
// Create a new Serialize instance
const serialize = new Serialize(this);
// Log the results of the instance methods
console.log(serialize.string());
console.log(serialize.array());
console.log(serialize.object());
console.log(serialize.json());
});
If you didn't need all of the methods, there would be no point in saving the instance to a variable, so you could just do something like this instead:
document.forms[0].addEventListener('submit', function (event) {
// Prevent the default submission
event.preventDefault();
// Serialize the data into a query string
const data = new Serialize(this).string();
// Log the data
console.log(data);
});
You can view a demo on CodePen.
If you're curious, you can also view the source code on GitHub.