Issue
I want to delete a row from LocalStorage
This Method Works properly But it is removing the last row only, when i refresh it so instead of what i have clicked is not deleting
so please help me to get this issue resolve in simple word i want to delete that row from localstorage, so when i reload the page so it will not be appear
js file
console.log('This is ES6 version of project 2');
const uid = function () {
return Date.now().toString(36) + Math.random().toString(36).slice(2);
};
class Book {
constructor(name, author, type) {
this.id = uid();
this.name = name;
this.author = author;
this.type = type;
}
}
class Display {
add(book) {
console.log('Adding to UI');
let tableBody = document.getElementById('tableBody')
let uiString = `<tr class="tableBody" id="tableBody" data-id="${book.id}">
<td id="search">${book.name}</td>
<td>${book.author}</td>
<td>${book.type}</td>
<td><input type="button" value="Delete Row" class="btn btn-outline-danger" onclick="RemoveRow(this)"></td>
</tr>`;
tableBody.innerHTML += uiString;
// save the data to the browser's local storage -----
const books = JSON.parse(localStorage.getItem("books"));
// console.log(books);
if (!books.some((oldBook) => oldBook.id === book.id)) books.push(book);
localStorage.setItem("books", JSON.stringify(books));
}
clear() {
let libraryForm = document.getElementById('libraryForm');
libraryForm.reset();
}
validate(book) {
if (book.name.length < 2 || book.author.length < 2) {
return false;
}
else {
return true;
}
}
show (type, displayMessage) {
let message = document.getElementById('message');
let boldText;
if (type === 'success'){
boldText = 'Success';
}
else{
boldText = 'Error!';
}
message.innerHTML = `<div class="alert alert-${type} alert-dismissible fade show" role="alert">
<strong>${boldText}:</strong> ${displayMessage}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>`
setTimeout(function () {
message.innerHTML = '';
}, 5000);
}
}
// Add submit event listener to libraryForm
let libraryForm = document.getElementById('libraryForm');
libraryForm.addEventListener('submit', libraryFormSubmit);
function libraryFormSubmit(e) {
console.log('You have submitted library form')
let name = document.getElementById('bookName').value;
let author = document.getElementById('author').value;
let type;
let fiction = document.getElementById('fiction');
let programming = document.getElementById('programming');
let cooking = document.getElementById('cooking');
if (fiction.checked) {
type = fiction.value;
}
else if (programming.checked) {
type = programming.value;
}
else if (cooking.checked) {
type = cooking.value;
}
let book = new Book(name, author, type);
console.log(book);
let display = new Display();
if (display.validate(book)) {
display.add(book);
display.clear();
display.show('success', 'Your book has been successfully added')
}
else {
// show error to the user
display.show('danger', 'Sorry you cannot add this book.')
}
e.preventDefault();
}
(() => {
const display = new Display();
let books = localStorage.getItem("books");
if (books) {
books = JSON.parse(books);
books.forEach((book) => display.add(book));
}
else
localStorage.setItem("books", JSON.stringify([]));
})();
function RemoveRow(index) {
let td1 = event.target.parentNode;
let tr1 = td1.parentNode;
tr1.parentNode.removeChild(tr1);
const books = JSON.parse(localStorage.getItem("books"));
// books.pop(books);
const newBooks= books.filter(book=> book.id !== index).pop();
localStorage.setItem("books", JSON.stringify(newBooks));
}
html file
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"
integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
<title>Welcome to Juggu library</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark ">
<div class="container-fluid">
<a class="navbar-brand" href="/index.html"><b> Juggu library </b></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="/index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/about.html">About Us</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown"
aria-expanded="false">
Websites
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="//allyouneed-notesapp.netlify.app/index.html">AllYouNeed Notes App</a>
<a class="dropdown-item" href="//textutilssystem.herokuapp.com">Text Utils</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="//github.com/Mohammedvaraliya">github Profile</a>
</div>
</li>
</ul>
<form class="d-flex" role="search">
<input class="form-control me-2" type="search" id="searchTxt" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<div id="message">
<!-- <div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>Holy guacamole!</strong> You should check in on some of those fields below.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div> -->
</div>
<div class="container my-3" id="notes">
<form id="libraryForm">
<h1>Juggu library</h1>
<hr>
<div class="form-group row">
<label for="bookName" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="bookName" placeholder="Book Name">
</div>
</div>
<div class="form-group row">
<label for="Author" class="col-sm-2 col-form-label">Author</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="author" placeholder="Author">
</div>
</div>
<fieldset class="form-group row">
<legend class="col-form-label col-sm-2 float-sm-left pt-0">Type</legend>
<div class="col-sm-10">
<div class="form-check">
<input class="form-check-input" type="radio" name="type" id="fiction" value="fiction" checked>
<label class="form-check-label" for="fiction">
Fiction
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="type" id="programming" value="programming">
<label class="form-check-label" for="Programming">
Computer Programming
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="type" id="cooking" value="cooking">
<label class="form-check-label" for="cooking">
Cooking
</label>
</div>
</div>
</fieldset>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary" id="addBtn">Add Book</button>
</div>
</div>
</form>
<div id="table">
<h1>Your Books</h1>
<table class="table table-dark table-striped">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Author</th>
<th scope="col">Type</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody class="tableBody" id="tableBody"> </tbody>
</table>
</div>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
<!-- <script src="js/index.js"></script> -->
<script src="js/indexes6.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"
integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF"
crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.min.js" integrity="sha384-VHvPCCyXqtD5DqJeNxl2dtTyhF78xXNXdkwX1CZeRusQfRKp+tA7hAShOK/B/fQ2" crossorigin="anonymous"></script>
-->
</body>
</html>
Solution
Inside your add
function, pass book.id
to RemoveRow instead of this
so that RemoveRow
function gets the correct id of the book to remove
let uiString = `<tr class="tableBody" id="tableBody" data-id="${book.id}">
<td id="search">${book.name}</td>
<td>${book.author}</td>
<td>${book.type}</td>
<td><input id="${book.id}" type="button" value="Delete Row" class="btn btn-outline-danger" onclick="RemoveRow(this)"></td>
</tr>`;
I found a couple of more issues, in your RemoveRow function you don't have to use pop
function RemoveRow(element) {
const bookId = element.id;
let td1 = document.getElementById(bookId).parentNode;
let tr1 = td1.parentNode;
tr1.parentNode.removeChild(tr1);
const books = JSON.parse(localStorage.getItem('books')) || [];
const newBooks = books.filter((book) => book.id !== bookId);
localStorage.setItem('books', JSON.stringify(newBooks));
}
And in your add
function, when retrieving books for the first time books will be null
, so initialize it to an empty array.
....
tableBody.innerHTML += uiString;
// save the data to the browser's local storage -----
const books = JSON.parse(localStorage.getItem('books')) || [];
....
Answered By - Abito Prakash
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.