It is good practice to use a <form>
element when handling multiple inputs simultaneously. The form element can access all of the inputs it has inside of it. This way you won't have to select each individual input but can select and process them all together.
So start with the form wrapping. Then instead of listening for the onclick
on the <input type="button" value="submit" onclick="submit()">
, listen for the submit
event on the form element.
It is considered best practice to listen to events by using the .addEventListener()
method. This way you can set multiple event handlers to a single event without overwriting the onclick
or onsubmit
property of an element. Chris Baker does an excellent job explaining it in this SO post.
So now that you have a form, how do we get the data out of it? You could use the modern class of FormData. FormData
creates an iterable object, which means we can loop over it using for..of, that holds all the names and values of the inputs in a form. It also has methods to add, remove and get the keys or values from the object. The FormData
constructor can take a <form>
element as argument like so:
var formElement = document.querySelector('form'); // Select the form.
var formData = new FormData(form); // Pass the form into the FormData class.
Now the formData
variable holds all of the names and values of the form.
I've added a working example for you to try out. Please read up on the documentation I provided you to understand what is going on and what you can do with it.
Quick sidenote: FormData
and the for..of
loop are relatively new and are not supported in IE. If that is a dealbreaker I would suggest you don't use the FormData
constructor and simply loop over the elements within the form.
Edit: I changed to loop from formData.values()
to formData
to get both the name
and value
attributes of each input. This is identical to formData.entries()
as show in the MDN documents.
// Create storage for the values.
var values = [];
// Get the form element.
var form = document.getElementById('form');
// Add the submit event listener to the form.
form.addEventListener('submit', submit);
function submit(event) {
// Get the data from the form.
// event.target represents the form that is being submitted.
var formData = new FormData(event.target);
// Loop over each pair (name and value) in the form and add it to the values array.
for (var pair of formData) {
values.push(pair);
}
// Log the values to see the result.
console.log(values);
// Prevent the form from default submitting.
event.preventDefault();
}
<div class="players">
<!-- Wrap a form around the inputs -->
<form id="form">
<div id="wrapper">
<span>Name: <input type="text" name="name"> Dex modifier: <input type="text" name="dex"></span>
</div>
<input type="button" value="add player" onclick="add_fields()">
<!-- Notice type="submit" instead of type="button". This is important -->
<input type="submit" value="submit">
</form>
</div>