Imagine you are designing a registeration page and there are numerous input fields, buttons and so on. Would you keep on defining reference for each and every field to access the data, no right? Theres a necessity for a shortcut or a command which will make our work easier, here's where Form Data comes into picture.
FormData provides a interface to define and access these fields disguised as set of key/value pair.The FormData() function (constructor) lets you create a object of FormData.
var formData=new FormData(form) // here form in brackets is the name or the class/id name of the form
Methods of FormData()
Methods are actions that can be performed on objects.Here are the methods of FormData() :
-
append()
As the name suggest append() adds new value to the existing value of a key or creates a new key and adds the value.
formData.append( 'username' , 'John' ); // here 'username' is the key name and 'John' is the value which youll be appending
-
delete()
Using this youll be able to delete a key and its corresponding value of a object.
formData.delete(name); // here 'name' is the key name
-
entries()
This method will return you a array or key-value pair
formData.entries();
// Eg We have a form with id name form and input fields as follows
<input="text" name="key1" value="value1">
<input="text" name="key2" value="value2">
//Then using formData.entries will give us array [ key1,value1 ] and [key2,value2] -
get() and getAll()
get() returns the value of the first key(name) while getAll() returns a array of values which the same key(name)
formData.get(name); // here name is the key name
formData.getAll(name); // here name is the key name, and returns a array for values with name key. -
has()
This return a boolean value i.e true/false in response to the present of value.
formData.has(name); // So if the key 'name' is has its corresponding value it returns true else returns false
-
keys()
Returns an array of keys (names) under the object.
formData.has(name); // So if the key 'name' is has its corresponding value it returns true else returns false
-
values()
Returns of array of all values under the object
formData.values(); // Returns array of values.