第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 FormData 將表單轉換為對象數(shù)組

使用 FormData 將表單轉換為對象數(shù)組

牛魔王的故事 2023-07-20 17:09:56
我正在開發(fā)一種用戶可以添加或刪除朋友信息的表單。我當前的代碼如下所示:(() => {  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++;    });
查看完整描述

1 回答

?
UYOU

TA貢獻1878條經(jīng)驗 獲得超4個贊

這就是我解決問題的方法。??

我添加了評論以使其易于理解。?


(() => {

  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}]`);

      });

      clone

        .querySelector(".textarea")

        .setAttribute("name", `textarea[${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++;

    });


  theForm.addEventListener("submit", (event) => {

    event.preventDefault();


    const theArray = [];

    const theFormData = new FormData(theForm);


    // cycle through FormData keys

    for(const [key, value] of theFormData.entries()) {

    

        if (!value) {

          // do validation here

          return;

        }


      // get the key number

      const keyNumber = key.match(/\d/g).join('');

      // assign the object to theArray variable

      theArray[keyNumber] = {

        'first_name': theFormData.get(`firstName[${keyNumber}]`),

        'middle_name': theFormData.get(`middleName[${keyNumber}]`),

        'last_name': theFormData.get(`lastName[${keyNumber}]`),

        'checkbox': theFormData.getAll(`checkbox[${keyNumber}]`),

        'radio': theFormData.get(`radio[${keyNumber}]`),

        'textarea': theFormData.get(`textarea[${keyNumber}]`)

      }      


    }

    

    // clean theArray before sending to the back-end

    const filteredArray = theArray.filter(Boolean);

    console.log(filteredArray);


  });

})();

.set {

  margin: 5px;

  padding: 5px;

  outline: 1px solid #ccc;

}

.removeSet {

  float: right;

}

<form id="theForm">

  <template>

    <div class="set">

      <button class="removeSet">remove</button>

      <input class="first_name" placeholder="first name" /><br>

      <input class="middle_name" placeholder="middle name" /><br>

      <input class="last_name" placeholder="last name" /><br>

      <!-- checkbox -->

      <label><input type="checkbox" class="checkbox" value="checkbox a" />checkbox a</label>

      <label><input type="checkbox" class="checkbox" value="checkbox b" />checkbox b</label>

      <label><input type="checkbox" class="checkbox" value="checkbox c" />checkbox c</label><br>

      <!-- radio -->

      <label><input type="radio" class="radio" value="radio a" />radio a</label>

      <label><input type="radio" class="radio" value="radio b" />radio b</label>

      <label><input type="radio" class="radio" value="radio c" />radio c</label><br>

      <!-- textarea -->

      <textarea class="textarea" rows="4" cols="50">additional notes</textarea>

    </div>

  </template>

  <button id="addMoreFields">add</button>

  <button id="submitForm" style="display: none;">submit</button>

</form>


查看完整回答
反對 回復 2023-07-20
  • 1 回答
  • 0 關注
  • 322 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號