<form class="reduce-form">
<fieldset>
<input type="text" name="firstname" placeholder="Enter first name" /><br/>
<input type="text" name="lastname" placeholder="Enter last name"><br/>
<input type="email" name="email" placeholder="Enter e-mail" /><br/>
<button type="submit">Submit</button>
</fieldset>
</form>
*{
box-sizing:border-box;
font-family: 'Georgia';
font-size:14px;
}
fieldset{
border:0;
}
input{
margin-bottom:5px;
border:1px solid #ddd;
height:34px;
padding:5px;
width:250px;
}
button{
width:250px;
background:#1BBC9B;
color:white;
border:0;
height:34px;
}
//1. We want to run over all .reduce-form's and add an eventListener to their submit buttons
document.querySelectorAll('.reduce-form').forEach(form => {
form.addEventListener('submit', (event) => {
event.preventDefault();
//2. create an array of all elements with a [name] attribute within the submitted form
const elArr = [...event.currentTarget.querySelectorAll('*[name]')];
//3. Reduce! Where the magic happens
const formData = elArr.reduce((prev, next, index, array) => {
const inputName = next.getAttribute('name');
const inputValue = next.value;
prev[inputName] = inputValue;
return prev;
}, {});
console.log('formData', formData);
//4. we can use fetch() or whatever you like to send our formData. Not important for now.
});
});