Get Form Input Fields As Query String in Javascript

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

console.log(form_str);

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

Note that the ? character will not be included.

In this Tutorial
    Comments
    Loading Comments