Cleaner way to get an array of values from a form

Greetings all!

I’m currently building a simple book log, and am having a bit of trouble with forms.
The goal is to use an event listener to activate with the submit event, then gather all of the inputs into an array so that I can create a custom object.

I’ve found a very basic way of doing this, but I’m wondering if there is a better (cleaner?) way?

let valueList = [];
document
    .querySelectorAll('input[type="text"]')
    .forEach(element => valueList.push(element.value));

This would be inside an event listener.

I think you can’t use forEach on a HTMLcollection

Huh, after a search this shouldn’t work… but it is…
Well, I’d rather not get into the habit of building things with broken rules, so for safeties sake I changed it to:

 [...document
    .querySelectorAll('input[type="text"]')]
    .forEach(element => valueList.push(element.value));

Thanks for spotting that.

I am not sure why you’re running a spread operator with a foreach loop.

Edit: sorry I read the code wrong everything seems fine.

My preferred way to work with forms in vanilla JS is using formData. Since you mentioned your inputs are part of the form, this makes things easier to grasp imho.

It’s almost a one liner :slight_smile:

 <form id="formElem">
  <input type="text" name="name" value="John">
  <input type="text" name="surname" value="Smith">
  <input type="submit">
</form>
  formElem.onsubmit = (e) => {
    e.preventDefault();
    let data = new FormData(formElem)
    for (v of data) {
      console.log(v)
    }
  }
// on submit it will log
// [ 'name', 'John' ]
// [ 'surname', 'Smith' ]

Hope this helps.

1 Like