I’ve made a form that pops up and now I want to store the input values in 3 separate values in the array const book.
The project will be a library app where you’ll ultimately be able to remove/add books, and it’s apart of The Odin Project’s curriculum.
Here is my repository: https://github.com/Rutchyy/library (focus around line 53 in the app.js file.)
const book = submit.addEventListener("click", (event) => {
event.preventDefault();
let name = newForm.firstChild.firstChild // How do I navigate to the title input?
console.log(name)
})
And the HTML:
<form method="get" id="new-book-form">
<div>
<label for="title">Title</label>
<input type="text" id="title" name="title">
</div>
<div>
<label for="author">Author</label>
<input type="text" id="author" name="author">
</div>
<div>
<label for="pages">Pages</label>
<input type="number" id="pages" name="pages">
</div>
<button id="create-book">Create Book</button>
</form>
>Solution :
submit.addEventListener("click", (event) => {
event.preventDefault();
// book variable be edited afterwards
let book = []
//select all inputs of the form
document.querySelectorAll('#new-book-form input').forEach(e =>{
book.push(e.value)
})
console.log(book)
})
At first I created an empty array, then fetched all inputs of the form by querySelectorAll() which selects all elements matching css selector #new-book-form input, then for each of them, I inserted their value to the array.
Hope it helps ^_^