Home > other >  Javascript: How to get ID of input in FormData?
Javascript: How to get ID of input in FormData?

Time:12-30

I have a form of checkboxes. On submit, I get the FormData object and get access to the name and value of the selected checkboxes. However, I also need the unique ID identifier in order to properly POST the data to my backend. Looking through SO and the Mozilla docs, I have not found a way to get access to the ID property in addition to the name and value.

How do I get access to the id property on a selected input? Thanks for the help!

HTML

<form>
  <label>
    <input type="checkbox" name="customerResponse" value="Twitter" id="221"/>
    <span>Twitter</span>
  </label>
  <label>
    <input type="checkbox" name="customerResponse" value="IG" id="222"/>
    <span>IG</span>
  </label
  <label>
    <input type="checkbox" name="customerResponse" value="FB" id="223"/>
    <span>FB</span>
  </label
</form>

Javascript

function logSubmit(form) {

    let data = new FormData(form);
    let testarr = []
    for (const [name, value] of data) {
      if (value !="") testarr.push([{responseName: name},{customerResponse: value}])
    }

    console.log(testarr);
}

CodePudding user response:

You can use element.id like this:

var idStr = element.id; // Get the id

MDN

CodePudding user response:

I think you can't use FormData to get the ID, but you can use below code:

$(form).find('input:checked').each((e, value) => {
                console.log(value.id);
                //Here you can use value.id 
            });
  • Related