Hello, I’m stuck on a toggle button that I created inside a table and I want to change the text and value of a book’s read status from yes to no and viceversa.
I managed to create an event inside the addBookToList() function.
When I click the toggle button, it fires an alert but I don’t know how to change the value and text inside the table (and also update the new value in the Local Storage).
HTML:
<div class="heading">
<h1>Library App</h1>
</div>
<div class="main-div">
<div class="para-div">
<p>Click the button below and add a new book to the list</p>
<button id="addBook-btn">+ ADD BOOK</button>
</div>
<form action="#" class="form">
<label for="title">Title</label>
<input type="text" id="title" required>
<label for="author">Author</label>
<input type="text" id="author" required>
<label for="num-pages">No. of pages</label>
<input type="number" id="num-pages" required>
<br>
<span>Have you read this book?</span>
<br>
<input type="radio" name="radio" id="yes" value="yes" checked>
<label for="yes" class="yes">Yes</label>
<input type="radio" name="radio" id="no" value="no">
<label for="no" class="no">No</label>
<div class="button-div">
<button id="add-btn" type="submit">SUBMIT</button>
<button id="cancel-btn" type="submit">CANCEL</button>
</div>
</form>
</div>
<div class="table-box">
<hr>
<table>
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>No. of pages</th>
<th>Read</th>
</tr>
</thead>
<tbody class="list"></tbody>
</table>
</div>
JS:
// DOM values
let form = document.querySelector('.form');
const list = document.querySelector('.list');
// Book constructor
function Book(author, title, pages, read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
}
// Event listener when clicking SUBMIT button on the form
form.addEventListener('submit', (e) => {
e.preventDefault();
// Get values from User
let title = document.querySelector('#title').value;
let author = document.querySelector('#author').value;
let pages = document.querySelector('#num-pages').value;
let read = getRead();
// Instantiate book
const book = new Book(author, title, pages, read);
// Push book to the library and show it on the UI
myLibrary.push(book);
addBookToList();
});
function addBookToList() {
const row = document.createElement('tr');
myLibrary.forEach(value => {
// Add the book to the table
row.innerHTML = `
<td>${value.title}</td>
<td>${value.author}</td>
<td>${value.pages}</td>
<td>${value.read}</td>
<td><button class="toggle">Change read status</button></td>
<td><a href="#" class="btn delete">X</a></td>`;
list.appendChild(row);
const toggleBtn = document.querySelector('.toggle');
toggleBtn.onclick = (function(value) {
return function(){
value.read = !value.read;
console.log(value.read);
alert(value.read);
}
})(value);
});
}
// Get value of radio button
function getRead() {
const radioBtn = document.querySelectorAll('input[name="radio"]');
let selectValue;
for(const i of radioBtn) {
if(i.checked) {
selectValue = i.value;
}
}
return selectValue;
}