-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocalStorage.js
67 lines (54 loc) · 2.1 KB
/
localStorage.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
// Function to add a user to Local Storage
function addUserToLocalStorage(user) {
let userList = JSON.parse(localStorage.getItem('userList') || '[]');
userList.push(user);
localStorage.setItem('userList', JSON.stringify(userList));
}
// Function to display users in the UI
function displayUsers() {
const userList = document.getElementById('userList');
userList.innerHTML = '';
const storedUsers = JSON.parse(localStorage.getItem('userList') || '[]');
storedUsers.forEach((user, index) => {
const listItem = document.createElement('li');
listItem.innerHTML = `
<span>${user.name} - ${user.email} - ${user.phone}</span>
<button onclick="editUser(${index})">Edit</button>
<button onclick="deleteUser(${index})">Delete</button>
`;
userList.appendChild(listItem);
});
}
// Function to delete a user from Local Storage and UI
function deleteUser(index) {
const storedUsers = JSON.parse(localStorage.getItem('userList') || '[]');
storedUsers.splice(index, 1);
localStorage.setItem('userList', JSON.stringify(storedUsers));
displayUsers();
}
// Function to edit a user's email
function editUser(index) {
const storedUsers = JSON.parse(localStorage.getItem('userList') || '[]');
const newEmail = prompt('Enter new email:');
if (newEmail) {
storedUsers[index].email = newEmail;
localStorage.setItem('userList', JSON.stringify(storedUsers));
displayUsers();
}
}
// Event listener for form submission
document.getElementById('userForm').addEventListener('submit', function (e) {
e.preventDefault();
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const phone = document.getElementById('phone').value;
const user = { name, email, phone };
addUserToCloudStorage(user);
displayUsers();
// Clear form fields
document.getElementById('name').value = '';
document.getElementById('email').value = '';
document.getElementById('phone').value = '';
});
// Initial display of users
displayUsers();