I’m on Library Project. The new book button is for adding books, and when i try adding another book, it duplicates. So I added container.textContent = '';
on my display function to remove duplicates. I successfully added one book, but when i tried adding another book, the modal doesn’t show up anymore and I inspected in on edge. This is what it says: Uncaught InvalidStateError: Failed to execute ‘showModal’ on ‘HTMLDialogElement’: The element is not in a Document. at HTMLButtonElement.
(even tho i have dialog.showModal(); and my dialog is present on html)
Here is my html:
`<dialog id = 'dialog'>
<form>
<fieldset>
<label for="title">Title</label>
<input type="text" id="title" name="title">
<label for="author">Author</label>
<input type="text" id="author" name="author">
<label for="pages">Pages</label>
<input type="number" id="pages" name="pages">
</fieldset>
<fieldset>
<legend>Have you read it?</legend>
<div class = 'yes'>
<input type="radio" id="read" name="read" value="read">
<label for="read">Yes</label>
</div>
<div class = 'no'>
<input type="radio" id="not_read" name="read" value="not_read">
<label for="not_read">No</label>
</div>
</fieldset>
<div class = 'btn_submit'>
<button id = 'submit' type="submit">Submit</button>
</div>
</form>
</dialog>`
My Javascript:
`document.addEventListener(‘DOMContentLoaded’, () => {
const container = document.querySelector('.container')
const Btn = document.querySelector('#mybtn');
const dialog = document.querySelector('#dialog');
const submitBtn = document.querySelector('#submit');
const myLibrary = [];
function Book (title,author,pages,read){
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
this.info = function(){
return `Title: ${this.title}
Author: ${this.author}
Pages: ${this.pages}
Read: ${this.read}`;
}
}
function addBookToLibrary() {
const title = document.querySelector('#title').value;
const author = document.querySelector('#author').value;
const pages = document.querySelector('#pages').value;
const read = document.querySelector('input[name="read"]:checked').value;
const newBook = new Book(title,author,pages,read);
myLibrary.push(newBook)
}
/*
let addAnother = true;
while(addAnother){
addBookToLibrary()
addAnother = prompt("Would you like to add another book? ") == 'yes';
}*/
function display(){
container.textContent = '';
myLibrary.forEach(lib => {
const book = document.createElement('div');
book.classList.add('book');
const newP = document.createElement('p');
book.appendChild(newP);
container.appendChild(book);
newP.textContent = lib.info();
})
}
Btn.addEventListener('click', () =>{
dialog.showModal();
});
submitBtn.addEventListener('click', (event) =>{
addBookToLibrary();
display();
event.preventDefault();
dialog.close();
});
});
`
I’d appreciate answers, thank you.