Browser - FormData (Web API)

1 - About

FormData is a web api object that represent the data of a form.

You can create/build it and use it:

3 - Process

The formData is populated by following this procedure: constructing-the-form-data-set

4 - Example

4.1 - Build from the form


<form id="form1" onsubmit="handleSubmit(); return false;">
<input name="user" type="text" value="Nico" />
<input name="age" type="number" value="10" />
<input name="button" type="submit" value="Let mee see the input data !" />
</form>


handleSubmit = () => {
  // build the formData object
  let formData =  new FormData(document.getElementById('form1'));
  // retrieve the entries in a entries variable of iterator type
  let entries = formData.entries();
  // loop over the iterator
  let result = entries.next();
  while (!result.done) {
    console.log("Input: Name: "+result.value[0]+", value: "+result.value[1]);
    result = entries.next();
  }
}

  • Result:

5 - Management

5.1 - Create

5.1.1 - Manually


let formData = new FormData();
formData.append('username', 'Nico');
formData.append('age', '10');

5.1.2 - Form

From a form, only successful form controls are included, i.e. those:

  • with a name,
  • not disabled
  • checked for radio buttons and checkboxes)
  • or selected one or more options within a select.

let formData =  new FormData(document.getElementById('form1'));

5.2 - Read

The entries of a formData return an iterator.

Example:


let formData = new FormData();
formData.append('username', 'Nico');
formData.append('age', '10');
// The entries function returns an iterator
let it = formData.entries();

  • The loop (iteration)

let result = it.next();
while (!result.done) {
 console.log(result.value); 
 result = it.next();
}

5.3 - Event

The formdata event is fired when a form is constructing the entry list of the form data. You could then add data in the list.


<form id="form1" onFormData="handleFormData(event);">
<input name="button" type="submit" value="Let mee see the formDataEvent !" />
</form>


handleFormData = (FormDataEvent) => {
   alert('Received the event '+FormDataEvent.__proto__.toString());
}


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap