HTML — An easy way to capture all input values from a form

Sam Tomashi
2 min readMay 8, 2021
Photo by Florian Olivo on Unsplash

Capturing all input values from a HTML form can be hectic sometimes, especially for beginners. Fortunately there are different techniques that can be used to achieve that, some developers prefer to use JavaScript Libraries others prefer to use vanilla JS.

Deciding what technique to use heavily depends on your requirements, for instance you might find yourself in a scenario where you have to clean/process the user inputs before submitting the data to the back-end. Installing a library just to capture user inputs sounds a bit too much to me, since we never even use most of the functionalities provided by a library.

Therefore, using your own vanilla code might be more efficient than using a library. My solution is to use the JavaScript FormData constructor to convert a form to an object then loop through it to process the data.

Using the following HTML form as an example:

Then the vanilla JavaScript code would like this:

JS code to capture all input values from a form

I am not saying that’s the only way to do it, you can explore the methods provided by the FormData constructor to refactor this code. For instance instead of using formData.keys() at line 7, you can use formData.entries() which will also return an iterator.

If you just want to submit the data probably through a post request without processing it on the front-end, you can just store all key values pairs in a variable then send as shown below.

That way you don’t even need a loop to clean/process each user inputs.

If you know a better way to achieve this kindly let us know in comments.

--

--

Sam Tomashi

If programming was magic, I would be the Wand and you the Bright. If it was a form of communication, I would be a multilingual who speaks Java, Python, C#, etc.