5
Author: VALENTINO GAGLIARDI
Translator: Frontend Xiaozhi
Source: valentinog

There are dreams and dry goods. search 160cbf01f73498 [Great Move to the World] still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.

Q: How to use JS to get all fields of HTML form at once?

Consider a simple HTML form for saving tasks in a to-do list:

  <form>
    <label for="name">用户名</label>
    <input type="text" id="name" name="name" required>

    <label for="description">简介</label>
    <input type="text" id="description" name="description" required>

    <label for="task">任务</label>
    <textarea id="task" name="task" required></textarea>

    <button type="submit">提交</button>
  </form>

Each of the above fields has corresponding type , ID and name attributes, and the associated label . After the user clicks the "Submit" button, how do we get all the data from this form?

There are two methods: one is to use black technology and the other is to be cleaner, which is also the most commonly used method. In order to demonstrate this method, we first create form.js and import it into the file.

Get form fields from event target

First, we Submit event on the form to stop the default behavior (they send data to the backend).

Then, use this.elements or event.target.elements access the form fields:

On the contrary, if we need to dynamically add more fields in response to some user interaction, then we need to use FormData .

Use FormData

First, we submit event on the form to stop the default behavior. Next, we construct a FormData object from the form:

const form = document.forms[0];

form.addEventListener("submit", function(event) {
  event.preventDefault();
  const formData = new FormData(this);
});

In addition to append() , delete() , get() , set() , FormData also implements Symbol.iterator . This means it can be traversed for...of

const form = document.forms[0];

form.addEventListener("submit", function(event) {
  event.preventDefault();
  const formData = new FormData(this);

  for (const formElement of formData) {
    console.log(formElement);
  }
})

clipboard.png

clipboard.png

In addition to the above methods, the entries() method obtains the form object form:

const form = document.forms[0];

form.addEventListener("submit", function(event) {
  event.preventDefault();
  const formData = new FormData(this);
  const entries = formData.entries();
  const data = Object.fromEntries(entries);
});

This is also suitable for Object.fromEntries() (ECMAScript 2019)

Why is this useful? As follows:

const form = document.forms[0];

form.addEventListener("submit", function(event) {
  event.preventDefault();
  const formData = new FormData(this);
  const entries = formData.entries();
  const data = Object.fromEntries(entries);

  // send out to a REST API
  fetch("https://some.endpoint.dev", {
    method: "POST",
    body: JSON.stringify(data),
    headers: {
      "Content-Type": "application/json"
    }
  })
    .then(/**/)
    .catch(/**/);
});

Once you have the object, you can use fetch send the payload.

Be careful : If you omit the name attribute on the form field, it is just not generated in the FormData object.

to sum up

To get all the fields from the HTML form, you can use:

  • this.elements or event.target.elements can only be used when all fields are known in advance and they remain stable.

Use FormData build an object with all fields, which can then be converted, updated or sent to the remote API. *


Original: https://www.valentinog.com/blog/form-data/

code is deployed, the possible bugs cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I recommend a useful BUG monitoring tool Fundebug .


communicate with

The article is continuously updated every week. You can search for [Great Read it for the first time, reply [Benefits] are multiple front-end videos waiting for you, this article GitHub https://github.com/qq449245884/xiaozhi has been included, welcome to Star.


王大冶
68.1k 声望105k 粉丝