Skip to content

Commit

Permalink
update function edit and delete product
Browse files Browse the repository at this point in the history
  • Loading branch information
viethg1995 committed Oct 15, 2023
1 parent bf711a2 commit f85ee68
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 5 deletions.
4 changes: 4 additions & 0 deletions asserts/js/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
let isLoading = true;

const includeHTML = () => {
let z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
Expand Down Expand Up @@ -28,4 +30,6 @@ const includeHTML = () => {
return;
}
}

isLoading = false;
};
28 changes: 24 additions & 4 deletions asserts/js/main/product.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
const getProducts = () => {
return JSON.parse(localStorage.getItem("products")) || [];
};

/**
* Show product
*/
const showProduct = () => {
const products = JSON.parse(localStorage.getItem("products")) || [];
const products = getProducts();
let productShow = "";
products.forEach((product, index) => {
productShow += `
Expand All @@ -11,8 +15,8 @@ const showProduct = () => {
<td>${product.name}</td>
<td>${product.price}</td>
<td>
<button>Sửa</button>
<button>Xóa</button>
<button onclick="editProduct(${index})">Sửa</button>
<button onclick="delProduct(${index})">Xóa</button>
</td>
</tr>
`;
Expand All @@ -24,7 +28,7 @@ const showProduct = () => {
const addProduct = () => {
const productName = document.getElementById("product-name").value;
const productPrice = document.getElementById("price").value;
const products = JSON.parse(localStorage.getItem("products")) || [];
const products = getProducts();
const product = {
name: productName,
price: productPrice,
Expand All @@ -33,3 +37,19 @@ const addProduct = () => {
localStorage.setItem("products", JSON.stringify(products));
showProduct();
};

const editProduct = (index) => {
const products = getProducts();
if (products.length === 0) return;

const product = products[index];
document.getElementById("product-name").value = product.name;
document.getElementById("price").value = product.price;
};

const delProduct = (index) => {
const products = getProducts();
products.splice(index, 1);
localStorage.setItem("products", JSON.stringify(products));
showProduct();
};
7 changes: 6 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@
<main w3-include-html="./pages/main/index.html"></main>
<script>
includeHTML();
showProduct();
const interval = setInterval(() => {
if (!isLoading) {
clearInterval(interval);
showProduct();
}
}, 1);
</script>
</body>
</html>

0 comments on commit f85ee68

Please sign in to comment.