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));
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:
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.
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' ]