Get Form Input Fields As Query String in Javascript

Published on December 20, 2020

Input fields inside a form can be retrieved as a query string using FormData & URLSearchParams objects.

<form id="sample-form">
	<input type="text" name="name" />
	<select name="gender">
		<option value="Male">Male</option>
		<option value="Male">Female</option>
	<input type="checkbox" name="terms" value="1" />I agree to Terms
let form_data = new FormData(document.querySelector("#sample-form"));
let form_str = new URLSearchParams(form_data).toString();


// name=&gender=Male
// name=John&gender=Male&terms=1

Note that the ? character will not be included.

In this Tutorial