-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
210 lines (153 loc) · 6.6 KB
/
main.js
File metadata and controls
210 lines (153 loc) · 6.6 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
// Yogev Bar
"use strict";
function addProduct() {
// Calls the 'saveToLocalStorage' function to save the product data
const isValid = saveToLocalStorage();
if (isValid === false)
return;
loadDataFromStorage();
}
function saveToLocalStorage() {
// Finding the HTML:
const productNameTextBox = document.getElementById("productName");
const productPriceTextBox = document.getElementById("productPrice");
const productCategoryTextBox = document.getElementById("productCategory");
const imageLinkTextBox = document.getElementById("imageLink");
// Extracts the values from the HTML input fields
let productName = productNameTextBox.value;
let productPrice = + productPriceTextBox.value;
let productCategory = productCategoryTextBox.value;
let imageLink = imageLinkTextBox.value;
const isValid = validator(productName, productPrice, productCategory, imageLink);
// Checks if the values are valid, if not returns false and exits the function
if (isValid === false)
return false;
// Creating an object from the current data of the product
const product = { productName, productPrice, productCategory, imageLink };
// Finding current array, if not exist I open a new:
/**
Initializes the products array from JSON data.
Parses the JSON string 'json' into an array using JSON.parse().
If the 'json' string is valid (for example null), it assigns the parsed array to 'productsArr'.
Otherwise, an empty array is assigned to 'productsArr'.
*/
let json = localStorage.getItem("products");
const productsArr = json ? JSON.parse(json) : [];
//push the new object to the array:
productsArr.push(product);
// Stringify the new array to be able save in local storage
const productsArrString = JSON.stringify(productsArr);
// Return the string to the local storage
localStorage.setItem("products", productsArrString);
// Resets the fields so that the user can conveniently insert the following product:
productNameTextBox.value = "";
productPriceTextBox.value = "";
// return the selection to the first value:
productCategoryTextBox.selectedIndex = 0;
imageLinkTextBox.value = "";
}
function validator(productName, price,productCategory, imageLink) {
//This function get the product name, price and imageLink
// return True if the values are valid, else False
// Finding the again the HTML textBox (for focus on them if the value not valid):
const productNameTextBox = document.getElementById("productName");
const productPriceTextBox = document.getElementById("productPrice");
const productCategoryTextBox = document.getElementById("productCategory");
const imageLinkTextBox = document.getElementById("imageLink");
// Checks if the product name has a valid length
if (productName.length < 3 || productName.length > 35) {
alert("Please insert a valid product name which contains at least 3 characters and maximum 34 chars");
productNameTextBox.focus();
return false;
}
//if the price is not a number , or a negative number or 0
//or bigger than 10000 so return false
// because its not valid
if (isNaN(price) || price <= 0 || price > 10000) {
alert("Please insert a valid price value that contain a positive number that smaller than 10000");
productPriceTextBox.focus();
return false;
}
if(productCategory==="Select product")
{
alert("You must select a category");
productCategoryTextBox.focus();
return false;
}
// Checks if the image link is a valid URL (min 8 chars):
if (imageLink.length < 8) {
alert("Please insert a valid url link that include minimum 8 chars");
imageLinkTextBox.focus();
return false;
}
// I don`t check the category because the user select her from list of valid values
// If we pass all the check successfully return true:
return true;
}
function loadDataFromStorage() {
// Finding the table container:
const cartContainer = document.getElementById("cartContainer");
//Loading local storage
const productString = localStorage.getItem("products");
// Parses a JSON string into a JavaScript object:
const products = JSON.parse(productString);
/*
Checks if the 'products' variable is null.
If 'products' is null, returns from the function.
Used to handle the case when no products are stored in the local storage.
*/
if (products === null)
return;
// Start to build a table in dynamic HTML:
let html = `
<table class="table table-hover">
<thead>
<tr>
<th>Product Name</th>
<th>Price</th>
<th>Category</th>
<th>Image</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
`;
// Build table rows for each item in 'products' using a for...of loop
for (const item of products) {
html +=
`
<tr>
<td>${item.productName}</td>
<td>${item.productPrice}</td>
<td>${item.productCategory}</td>
<td><img src=${item.imageLink} alt="Invalid link"></img></td>
<td>
<button onclick="deleteProduct('${item.productName}')">Delete</button>
</td>
</tr>`;
}
// Closing the HTML Container:
html += `</tbody></table>`;
// Insert the dynamic HTML table to the container:
cartContainer.innerHTML = html;
}
function deleteProduct(productName) {
// Retrieve the JSON string representing the products from the local storage
const productString = localStorage.getItem("products");
// Parse the JSON string into an array of products
const products = JSON.parse(productString);
// Create an empty array to store the updated products
const updatedProducts = [];
// Iterate over each product in the products array
for (let i = 0; i < products.length; i++) {
// Check if the current product's name does not match the specified productName
if (products[i].productName !== productName)
// If the name doesn't match, add the product to the updatedProducts array
updatedProducts.push(products[i]);
}
// Convert the updatedProducts array back into a JSON string
const updatedProductsString = JSON.stringify(updatedProducts);
// Update the "products" key in the local storage with the updated products string
localStorage.setItem("products", updatedProductsString);
loadDataFromStorage(); // Reload the table after deleting the product
}