I have built a page similar to this snippet.
const applyButton = document.querySelector(".filter-button");
applyButton.addEventListener("click", dummyFetchFunction);
function dummyFetchFunction(){
//here I want to read the input into an array.
//Then I will do the fetch passing this array as parameter.
}
.filter-button{
margin: 5px;
margin-top: auto;
border-radius: 5px;
}
.filter-group{
margin: 10px;
font-size: 13px;
}
.filter-group__title {
margin-bottom: 5px;
}
.filter-group__input {
display: flex;
}
.filter-group__input input {
width: 1%;
flex: 1 1 auto;
}
.filter-group__input span {
margin: 0 5px;
font-size: 1rem;
}
<div class="filter-group">
<div class="filter-group__title">
Publish year
</div>
<div class="filter-group__input">
<input type="text" placeholder="from" />
<span> - </span>
<input type="text" placeholder="to" />
</div>
</div>
<div class="filter-group">
<div class="filter-group__title">
Pages amount
</div>
<div class="filter-group__input">
<input type="text" placeholder="from" />
<span> - </span>
<input type="text" placeholder="to" />
</div>
</div>
<button class="filter-button">Apply filters</button>
My problem is I that I would like know is there any way to read data from multiple inputs into array Because right now the only thing that comes into my mind is to assign each input an Id and manually match push data into array.
3
Answers
You can give each input a name, then simply loop through the inputs in the form and add them to the object with their values. You don’t need to manually add them
If you would like to add the values to an array, I would recommend using a
form
element and listening to thesubmit
event. It will provide you with all of the values from the form, even if in development the layout and elements of the form change. See this answer for more information on this approach. If you want an array of values, you would just modify the for loop to add the values (pair[1]
) to an array.If you do NOT want to give each field a name and wrap in a form then we can use a Object assign of a map and object.fromEntries to make it easier to do dot notation
Here I only assume there are keys in the title div and inputs in the next div – The code does not care about names or IDs