I want to be able to extract the value from the input field and add it to a created div and each time a new div is created it will take a new value while leaving the old values in place. Right now the new value overwrites all of the other values.
If you see my example; the plus sign adds a book to the shelf, then submitting the input field should add a title. However, after adding subsequent books the previous titles are overwritten.
I appreciate any help.
const shelf = document.getElementById('shelf');
const addBookBtn = document.getElementById('add-book');
const submitFormBtn = document.getElementById('submitform');
function addBook() {
const book = document.createElement('div');
book.classList.add('book');
shelf.appendChild(book);
}
addBookBtn.addEventListener('click', function() {
addBook();
});
submitFormBtn.addEventListener('click', function(e) {
e.preventDefault();
var title = document.getElementById('booktitle').value;
var book = document.querySelectorAll('.book')
for (let b = 0; b < book.length; b++) {
book[b].textContent = title;
}
});
#shelf {
height: 150px;
border-bottom: 5px solid #000;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(25px, 40px));
align-items: end;
}
.book {
border: 1px solid #000;
height: 100px;
width: 25px;
display: inline-block;
}
<div id="bookshelf">
<div id="shelf"></div>
</div>
<button id="add-book">+</button>
<form>
<label for="booktitle">Book Title</label><br>
<input type="text" id="booktitle" name="booktitle"><br>
<input type="submit" id="submitform" value="Submit">
</form>
2
Answers
Don’t add the title to the divs in a loop. Use a global variable to hold the index of the book to add the title to. Every time you submit, you add the title to that book and increment the index.
simply do this test