使用 FormData 将表单转换为对象数组

我正在开发一种用户可以添加或删除朋友信息的表单。

我当前的代码如下所示:


(() => {

  let currentCount = 0;

  const theForm = document.querySelector("#theForm");


  document

    .querySelector("#addMoreFields")

    .addEventListener("click", (event) => {

      event.preventDefault();


      // find and clone the template content

      const template = theForm.getElementsByTagName("template")[0];

      const clone = template.content.cloneNode(true);

      const submitButton = document.querySelector("#submitForm");


      // if the submitButton is hidden, show it

      if (submitButton.offsetParent === null) {

        submitButton.removeAttribute("style");

      }


      // add class to set and name on input fields

      clone.querySelector(".set").classList.add(`set-${currentCount}`);

      clone

        .querySelector(".first_name")

        .setAttribute("name", `firstName[${currentCount}]`);

      clone

        .querySelector(".middle_name")

        .setAttribute("name", `middleName[${currentCount}]`);

      clone

        .querySelector(".last_name")

        .setAttribute("name", `lastName[${currentCount}]`);

      clone.querySelectorAll(".checkbox").forEach(function (item) {

        item.setAttribute("name", `checkbox[${currentCount}]`);

      });

      clone.querySelectorAll(".radio").forEach(function (item) {

        item.setAttribute("name", `radio[${currentCount}]`);

      });


      // remove button

      clone

        .querySelector(".removeSet")

        .setAttribute("id", `remove-${currentCount}`);

      clone

        .querySelector(".removeSet")

        .setAttribute("data-number", currentCount);


      theForm.append(clone);


      // add event listener to removeSet button

      document

        .querySelector(`#remove-${currentCount}`)

        .addEventListener("click", (event) => {

          event.preventDefault();

          const setName = `.set-${event.target.getAttribute("data-number")}`;

          document.querySelector(setName).remove();

        });


      currentCount++;

    });


牛魔王的故事
浏览 269回答 1
1回答

UYOU

这就是我解决问题的方法。😊我添加了评论以使其易于理解。✌(() => {&nbsp; let currentCount = 0;&nbsp; const theForm = document.querySelector("#theForm");&nbsp; document&nbsp; &nbsp; .querySelector("#addMoreFields")&nbsp; &nbsp; .addEventListener("click", (event) => {&nbsp; &nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; &nbsp; // find and clone the template content&nbsp; &nbsp; &nbsp; const template = theForm.getElementsByTagName("template")[0];&nbsp; &nbsp; &nbsp; const clone = template.content.cloneNode(true);&nbsp; &nbsp; &nbsp; const submitButton = document.querySelector("#submitForm");&nbsp; &nbsp; &nbsp; // if the submitButton is hidden, show it&nbsp; &nbsp; &nbsp; if (submitButton.offsetParent === null) {&nbsp; &nbsp; &nbsp; &nbsp; submitButton.removeAttribute("style");&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; // add class to set and name on input fields&nbsp; &nbsp; &nbsp; clone.querySelector(".set").classList.add(`set-${currentCount}`);&nbsp; &nbsp; &nbsp; clone&nbsp; &nbsp; &nbsp; &nbsp; .querySelector(".first_name")&nbsp; &nbsp; &nbsp; &nbsp; .setAttribute("name", `firstName[${currentCount}]`);&nbsp; &nbsp; &nbsp; clone&nbsp; &nbsp; &nbsp; &nbsp; .querySelector(".middle_name")&nbsp; &nbsp; &nbsp; &nbsp; .setAttribute("name", `middleName[${currentCount}]`);&nbsp; &nbsp; &nbsp; clone&nbsp; &nbsp; &nbsp; &nbsp; .querySelector(".last_name")&nbsp; &nbsp; &nbsp; &nbsp; .setAttribute("name", `lastName[${currentCount}]`);&nbsp; &nbsp; &nbsp; clone.querySelectorAll(".checkbox").forEach(function (item) {&nbsp; &nbsp; &nbsp; &nbsp; item.setAttribute("name", `checkbox[${currentCount}]`);&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; clone.querySelectorAll(".radio").forEach(function (item) {&nbsp; &nbsp; &nbsp; &nbsp; item.setAttribute("name", `radio[${currentCount}]`);&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; clone&nbsp; &nbsp; &nbsp; &nbsp; .querySelector(".textarea")&nbsp; &nbsp; &nbsp; &nbsp; .setAttribute("name", `textarea[${currentCount}]`);&nbsp; &nbsp; &nbsp; // remove button&nbsp; &nbsp; &nbsp; clone&nbsp; &nbsp; &nbsp; &nbsp; .querySelector(".removeSet")&nbsp; &nbsp; &nbsp; &nbsp; .setAttribute("id", `remove-${currentCount}`);&nbsp; &nbsp; &nbsp; clone&nbsp; &nbsp; &nbsp; &nbsp; .querySelector(".removeSet")&nbsp; &nbsp; &nbsp; &nbsp; .setAttribute("data-number", currentCount);&nbsp; &nbsp; &nbsp; theForm.append(clone);&nbsp; &nbsp; &nbsp; // add event listener to removeSet button&nbsp; &nbsp; &nbsp; document&nbsp; &nbsp; &nbsp; &nbsp; .querySelector(`#remove-${currentCount}`)&nbsp; &nbsp; &nbsp; &nbsp; .addEventListener("click", (event) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const setName = `.set-${event.target.getAttribute("data-number")}`;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.querySelector(setName).remove();&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; currentCount++;&nbsp; &nbsp; });&nbsp; theForm.addEventListener("submit", (event) => {&nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; const theArray = [];&nbsp; &nbsp; const theFormData = new FormData(theForm);&nbsp; &nbsp; // cycle through FormData keys&nbsp; &nbsp; for(const [key, value] of theFormData.entries()) {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if (!value) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // do validation here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; // get the key number&nbsp; &nbsp; &nbsp; const keyNumber = key.match(/\d/g).join('');&nbsp; &nbsp; &nbsp; // assign the object to theArray variable&nbsp; &nbsp; &nbsp; theArray[keyNumber] = {&nbsp; &nbsp; &nbsp; &nbsp; 'first_name': theFormData.get(`firstName[${keyNumber}]`),&nbsp; &nbsp; &nbsp; &nbsp; 'middle_name': theFormData.get(`middleName[${keyNumber}]`),&nbsp; &nbsp; &nbsp; &nbsp; 'last_name': theFormData.get(`lastName[${keyNumber}]`),&nbsp; &nbsp; &nbsp; &nbsp; 'checkbox': theFormData.getAll(`checkbox[${keyNumber}]`),&nbsp; &nbsp; &nbsp; &nbsp; 'radio': theFormData.get(`radio[${keyNumber}]`),&nbsp; &nbsp; &nbsp; &nbsp; 'textarea': theFormData.get(`textarea[${keyNumber}]`)&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // clean theArray before sending to the back-end&nbsp; &nbsp; const filteredArray = theArray.filter(Boolean);&nbsp; &nbsp; console.log(filteredArray);&nbsp; });})();.set {&nbsp; margin: 5px;&nbsp; padding: 5px;&nbsp; outline: 1px solid #ccc;}.removeSet {&nbsp; float: right;}<form id="theForm">&nbsp; <template>&nbsp; &nbsp; <div class="set">&nbsp; &nbsp; &nbsp; <button class="removeSet">remove</button>&nbsp; &nbsp; &nbsp; <input class="first_name" placeholder="first name" /><br>&nbsp; &nbsp; &nbsp; <input class="middle_name" placeholder="middle name" /><br>&nbsp; &nbsp; &nbsp; <input class="last_name" placeholder="last name" /><br>&nbsp; &nbsp; &nbsp; <!-- checkbox -->&nbsp; &nbsp; &nbsp; <label><input type="checkbox" class="checkbox" value="checkbox a" />checkbox a</label>&nbsp; &nbsp; &nbsp; <label><input type="checkbox" class="checkbox" value="checkbox b" />checkbox b</label>&nbsp; &nbsp; &nbsp; <label><input type="checkbox" class="checkbox" value="checkbox c" />checkbox c</label><br>&nbsp; &nbsp; &nbsp; <!-- radio -->&nbsp; &nbsp; &nbsp; <label><input type="radio" class="radio" value="radio a" />radio a</label>&nbsp; &nbsp; &nbsp; <label><input type="radio" class="radio" value="radio b" />radio b</label>&nbsp; &nbsp; &nbsp; <label><input type="radio" class="radio" value="radio c" />radio c</label><br>&nbsp; &nbsp; &nbsp; <!-- textarea -->&nbsp; &nbsp; &nbsp; <textarea class="textarea" rows="4" cols="50">additional notes</textarea>&nbsp; &nbsp; </div>&nbsp; </template>&nbsp; <button id="addMoreFields">add</button>&nbsp; <button id="submitForm" style="display: none;">submit</button></form>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript