Welcome to a quick tutorial on how to get the HTML form data in Javascript. So you have an HTML form but want to do the processing in Javascript instead?
To get the HTML form data in Javascript:
- Create the HTML form as usual – Give the form an ID, and attach a name to the input fields.
<form id="demo">
<input name="name">
- Create a form data object, and feed the HTML form in as a parameter.
var form = document.getElementById("demo");
var data = new FormData(form);
- Lastly, manually append more keys/values if required –
data.append("KEY", "VALUE");
That covers the quick basics, but read on for more examples!
TLDR – QUICK SLIDES
[web_stories_embed url=”https://code-boxx.com/web-stories/how-to-get-html-form-data-in-javascript/” title=”How To Get HTML Form Data In Javascript” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]
Fullscreen Mode – Click Here
TABLE OF CONTENTS
JAVASCRIPT GET FORM DATA
All right, let us now get into the examples of how to get the form data in Javascript.
EXAMPLE 1) GET FORM DATA & AJAX POST
<!-- (A) HTML FORM -->
<form id="demoA" onsubmit="return doForm()">
<input type="text" name="name" required value="Jon Doe">
<input type="email" name="email" required value="jon@doe.com">
<input type="submit" value="Go!">
</form>
<!-- (B) JS PROCESSING -->
<script>
function doForm () {
// (B1) FORM DATA - AUTO GET ALL FIELDS FROM "#DEMOA"
var data = new FormData(document.getElementById("demoA"));
// (B2) AJAX FETCH
fetch("SERVER-SCRIPT", { method:"post", body:data })
.then(res => res.text())
.then(txt => console.log(txt))
.catch(err => console.error(err));
// (B3) PREVENT DEFAULT FORM SUBMIT
return false;
}
</script>
This is the “complete example” of the above introduction snippet. All we need is to:
- Create the HTML
<form>
as usual. - Create a
new FormData(HTML FORM)
object, and submit it to the server “as usual”.
EXAMPLE 2) GET FORM DATA & URL PARAMS
<!-- (A) HTML FORM -->
<form id="demoB" onsubmit="return doForm()">
<input type="text" name="name" required value="Joe Doe">
<input type="email" name="email" required value="joe@doe.com">
<input type="submit" value="Go!">
</form>
<!-- (B) JS PROCESSING -->
<script>
function doForm () {
// (B1) FORM DATA - AUTO GET ALL FIELDS FROM "#DEMOB"
var data = new FormData(document.getElementById("demoB"));
// (B2) TO URL PARAMS
var params = new URLSearchParams(data).toString();
// (B3) AJAX FETCH
fetch("SERVER-SCRIPT?" + params)
.then(res => res.text())
.then(txt => console.log(txt))
.catch(err => console.error(err));
// (B4) OR REDIRECT - MIGHT AS WELL JUST SUBMIT THE FORM?
// location.href = "SERVER-SCRIPT?" + params;
// (B5) PREVENT DEFAULT FORM SUBMIT
return false;
}
</script>
This is an alternative for the folks who want to do GET
instead of POST
–
- (A & B1) The “usual HTML form” and create
var data = new FormData(HTML FORM)
. - (B2) Then, “convert” into
var params = new URLSearchParams(data)
. - (B3) Attach the parameters to the end of the URL –
"http://site.com?" + params.toString()
, and submit the form.
EXAMPLE 3) MORE FORM DATA
<!-- (A) HTML FORM -->
<form id="demoC" onsubmit="return doForm()">
<input type="text" name="name" required value="Joy Doe">
<input type="email" name="email" required value="joy@doe.com">
<div id="birthday">12 Mar 2077</div>
<input type="submit" value="Go!">
</form>
<!-- (B) JS PROCESSING -->
<script>
function doForm () {
// (B1) FORM DATA - AUTO GET ALL FIELDS FROM "#DEMOC"
var data = new FormData(document.getElementById("demoC"));
// (B2) MANUALLY APPEND MORE
data.append("birthday", document.getElementById("birthday").innerText);
data.append("gender", "female");
data.append("key", "value");
// (B3) FORM DATA YOGA
data.delete("key");
var name = data.get("name"); // Joy Doe
var hasEmail = data.has("email"); // true
for (let k of data.keys()) { console.log(k); }
for (let v of data.values()) { console.log(v); }
for (let [k, v] of data.entries()) { console.log(k, v); }
// (B4) PREVENT DEFAULT FORM SUBMIT
return false;
}
</script>
One last example to address a few common concerns.
- (A) Take note that the HTML form now has a “custom
<div id="birthday">
widget”. - (B1) Since the “custom widget” is not the usual
<input>
,var data = new FormData(FORM)
will not automatically adapt data from it. - (B2) To “fix” that, we can use
data.append("KEY", "VALUE")
to manually add more data entries. - (B3) Now, the
FormData
object is not some “black hole”. You put data in and have no idea what’s inside.get(KEY)
Returns the value of the specifiedKEY
.has(KEY)
Checks if the dataset containsKEY
.key()
Return all the keys in an array.values()
Return all the values in an array.entries()
Returns all the keys and values in an array.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
- Get Element By Id – MDN
- Form Data – MDN
- Submit Form Without Reloading – Code Boxx
- Display Message After Form Submit – Code Boxx
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!