In jQuery, it's easy to serialize form data into a query string using the serialize() method. But there's no point including an entire 30 KB library if that's all we need. As my friend Chris Ferdinandi puts it in The Lean Web, we go for the multi-purpose utility knife when the thing we really need is scissors. Instead, let's write our own, tiny helper function in vanilla JS.

First things first, let's create the function declaration:

/**
* Serialize all form data into a query string
* @param {HTMLFormElement} form The form
* @returns {String} The query string
*/

function serialize (form) {

}

Inside our function, the first thing we need to do is create a FormData object using the form element that was passed in. The FormData interface makes it easy to manipulate form data:

/**
* Serialize all form data into a query string
* @param {HTMLFormElement} form The form
* @returns {String} The query string
*/

function serialize (form) {
// Create a new FormData object
const formData = new FormData(form);
}

Next, we need to create a URLSearchParams object using our FormData object. The URLSearchParams interface makes it easy to manipulate query strings:

/**
* Serialize all form data into a query string
* @param {HTMLFormElement} form The form
* @returns {String} The query string
*/

function serialize (form) {
// Create a new FormData object
const formData = new FormData(form);

// Create a new URLSearchParams object
const params = new URLSearchParams(formData);
}

Finally, we need to return the query string by calling the toString() method on our URLSearchParams instance:

/**
* Serialize all form data into a query string
* @param {HTMLFormElement} form The form
* @returns {String} The query string
*/

function serialize (form) {
// Create a new FormData object
const formData = new FormData(form);

// Create a new URLSearchParams object
const params = new URLSearchParams(formData);

// Return the query string
return params.toString();
}

And there you have it! This helper function is available under the MIT license, so feel free to use it in your own projects: serialize.js.

It should work in all modern browsers, but not IE. If you use var instead of const, and include a polyfill for the URL interface (it comes with the default polyfill.io bundle), it should work back to IE10.

If you need to support IE9, my friend Chris Ferdinandi has a slightly more backwards-compatible version over at The Vanilla JS Toolkit.

View the demo on CodePen