javascript

Create form data in Javascript

Form data can be created in Javascript through a number of methods. One common method is to use the FormData object, which can be created from an HTML form element. This object can then be used to submit form data to a server.

var form = document.getElementsByTagName("form")[0];
var formData = new FormData(form);

formData.get("title"); //TO GET A KEY(KEY NAME WILL BE name attribute defined in your input controls)
formData.set("title", "This is new title"); //TO SET NEW VALUE TO A KEY

formData.delete("about"); //TO DELETE A KEY FROM FORM DATA

Form data can be required while making a post request in javascript. To create form data you just need to get the form(we used document.getElementsByTagName("form")[0] to get the form) and pass it to FormData(). Now you can pass it to your request if form data is required in the request.

Keys to remember:

  • 'name' attribute must be applied to the form control either it is input type, textarea or any other input type if you want to send its value in form data.
Was this helpful?