<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<div>
<table class="table table-bordered">
<thead>
<th>Id</th>
<th>Name</th>
<th>Phone</th>
<th>Age</th>
<th>Action</th>
</thead>
<tbody class="js--content"></tbody>
</table>
<div class="card p-4">
<button class="js--add btn btn-add btn-primary">Add user</button>
</div>
<form class="js--form card card--user p-4">
<input type="hidden" name="id">
<input class="form-control mb-1" type="text" name="name" placeholder="Name" required>
<input class="form-control mb-1" type="text" name="phone" placeholder="Phone" required>
<input class="form-control mb-3" type="number" name="age" placeholder="Age" min="18" required>
<button class="btn btn-primary mb-2 w-100" type="submit">OK</button>
</form>
<code class="card p-4">
<pre class="js--user user-info">
{ asd: 'asd' }
</pre>
</code>
</div>
table {
max-width: 800px;
margin: auto;
border-collapse: collapse;
}
table th,
table td {
border: 1px solid;
}
.card {
max-width: 400px;
margin: auto auto 20px;
}
.card--user {
display: none !important;
}
.card--user.open {
display: block !important;
}
function UserTable({ form, content, userInfo, addButton }) {
this.init = () => {
form.addEventListener('submit', (event) => {
event.preventDefault();
this.addUser(
form.elements.name.value,
form.elements.phone.value,
form.elements.age.value,
);
});
addButton.addEventListener('click', () => {
form.reset();
form.classList.add('open');
});
this.deleteUser()
this.loadUsers();
}
//Данный метод удаляет данные конкретного пользоаптеля
this.deleteUser = () => {
document.addEventListener('click', (event) => {
if (event.target.classList.contains('js--btn-delete')) {
const userID = event.target.closest('tr').dataset.id;
console.log('userID:', userID)
const userData = JSON.parse(localStorage.getItem('users'));
const filterUserData = userData.filter(item => item.id !== userID);
console.log('updateUserData:', filterUserData);
localStorage.setItem('users', JSON.stringify(filterUserData));
}
})
}
//Данный метод создает данные нового пользователя
this.addUser = (name, phone, age) => {
const user = {
id: Math.floor(Math.random() * 100),
name,
phone,
age,
}
this.userTemplate(user);
form.reset();
form.classList.remove('open');
const currentUsers = JSON.parse(localStorage.getItem('users')) || [];
currentUsers.push(user);
localStorage.setItem('users', JSON.stringify(currentUsers));
}
//Данный метод при перезагрузке страницы подшружает данные из LocalStorage на сайт в таблицу
this.loadUsers = () => {
const users = JSON.parse(localStorage.getItem('users'));
if (users) {
users.forEach(user => this.userTemplate(user));
}
}
//Создаем шаблон пользователя
this.userTemplate = (user) => {
content.insertAdjacentHTML('beforeend',(
`<tr data-id="${user.id}">`+
`<td class="userId">${user.id}</td>`+
`<td>${user.name}</td>`+
`<td>${user.phone}</td>`+
`<td>${user.age}</td>`+
`<td>`+
`<button class="btn">View</button>`+
`<button class="btn">Edit</button>`+
`<button class="btn js--btn-delete">Delete</button>`+
`</td>`+
`</tr>`
))
}
}
(new UserTable({
form: document.querySelector('.js--form'),
content: document.querySelector('.js--content'),
userInfo: document.querySelector('.js--user'),
addButton: document.querySelector('.js--add'),
})).init()
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.