-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
66 lines (53 loc) · 1.74 KB
/
script.js
File metadata and controls
66 lines (53 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const form = document.getElementById('book-form');
const bookList = document.getElementById('book-list');
// Load books from localStorage
document.addEventListener('DOMContentLoaded', loadBooks);
form.addEventListener('submit', function (e) {
e.preventDefault();
const bookName = document.getElementById('bookName').value;
const authorName = document.getElementById('authorName').value;
addBookToUI(bookName, authorName);
saveBookToStorage(bookName, authorName);
form.reset();
});
// Create table row dynamically
function addBookToUI(book, author) {
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${book}</td>
<td>${author}</td>
<td><button class="delete-btn">Delete</button></td>
`;
bookList.appendChild(tr);
}
// Delete book using event bubbling
bookList.addEventListener('click', function (e) {
if (e.target.classList.contains('delete-btn')) {
const row = e.target.parentElement.parentElement;
removeBookFromStorage(
row.children[0].textContent,
row.children[1].textContent
);
row.remove();
}
});
// Local Storage Functions
function getBooks() {
return JSON.parse(localStorage.getItem('books')) || [];
}
function saveBookToStorage(book, author) {
const books = getBooks();
books.push({ book, author });
localStorage.setItem('books', JSON.stringify(books));
}
function loadBooks() {
const books = getBooks();
books.forEach(item => addBookToUI(item.book, item.author));
}
function removeBookFromStorage(book, author) {
let books = getBooks();
books = books.filter(
item => !(item.book === book && item.author === author)
);
localStorage.setItem('books', JSON.stringify(books));
}