skip to Main Content

How to add an array to the last in this object:

const formElment = document.querySelector(".form");

formElment.addEventListener("submit", (event) => {
  event.preventDefault();

  var array = [];
  var checkboxes = document.querySelectorAll("input[type=checkbox]:checked");

  for (var i = 0; i < checkboxes.length; i++) {
    array.push(checkboxes[i].value);
    console.log(checkboxes[i].id);
  }

  const formData = new FormData(formElment);
  const data = Object.fromEntries(formData);
  
  console.log(data);

});

I used eventlistner for get form data and checkbox=checked. So now I want add those selected checkbox id to the end of the object and send through an API.

2

Answers


  1. I think you can add the values of array to FormData.

    formData.append("checkedValues", array.join(","));

    And then you can post your form to your API.

    Reference: https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

    Login or Signup to reply.
  2. You can add the checkbox values after you have created data using FormData and Object.fromEntries.

    Notice that the checkbox elements should not have a name attribute — then they are not included in the formData object.

    const formElment = document.forms.form01;
    
    formElment.addEventListener("submit", (event) => {
      event.preventDefault();
    
      let checkboxes = event.target.checkboxes.elements;
    
      let formData = new FormData(formElment);
      let data = Object.fromEntries(formData);
      data.checkboxes = [...checkboxes]
                          .filter(input => input.checked)
                          .map(input => input.value);
      console.log(data);
    });
    fieldset {
      border: none;
      margin: 0;
      padding: 0;
      display: inline;
    }
    <form name="form01">
      <input type="text" name="something" value="Testing 1 2 3">
      <fieldset name="checkboxes">
        <input type="checkbox" value="1">
        <input type="checkbox" value="2">
        <input type="checkbox" value="3">
      </fieldset>
      <button>Submit</button>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search