generated from microverseinc/readme-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext.js
68 lines (59 loc) · 1.84 KB
/
text.js
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
67
68
/* eslint-disable no-alert */
// Alternative method for for using JavaScript classes
class Books {
constructor(title, author) {
// Initializing useful variables
this.title = title;
this.author = author;
this.table = document.createElement('table');
this.tbody = document.createElement('tbody');
this.myForm = document.getElementById('form');
this.bookList = document.getElementById('book-list');
this.table.appendChild(this.tbody);
this.bookList.appendChild(this.table);
this.listTitle = document.querySelector('.list-title');
this.bookData = (localStorage.book != null) ? JSON.parse(localStorage.book) : [];
}
addBook() {
if (this.title.value === '' || this.author.value === '') {
this.listTitle.innerHTML = 'Please fill the field below';
} else {
this.bookData.push({ bookTitle: this.title.value, bookAuthor: this.author.value });
this.updateStore();
}
}
removeBook(id) {
this.bookData.splice(id, 1);
this.updateStore();
if (this.bookData.length === 0) {
this.listTitle.innerHTML = 'Books List is empty';
} else {
this.listTitle.innerHTML = '';
}
}
displayBooks() {
this.tbody.innerHTML = '';
let id = 0;
this.bookData.forEach((book) => {
this.tbody.innerHTML
+= `
<tr>
<td>
<strong>"${book.bookTitle}"</strong>
<span><strong>by ${book.bookAuthor}</strong></span>
</td>
<td class="remove" onClick="book.removeBook(${id})">Remove</td>
</tr>
`;
id += 1;
});
}
updateStore() {
localStorage.book = JSON.stringify(this.bookData);
this.displayBooks();
}
}
const title = document.getElementById('title');
const author = document.getElementById('author');
const book = new Books(title, author);
book.displayBooks();