Сохранение строк в таблице(Без jQuery)
У меня есть форма и таблица.
Данные в селекты берутся из json-файла(https://wbd.tlntq.com/web/webServices/getVars.php). После заполнения формы и нажатие на кнопку "save" Добавляется строка в таблицу. Помимо данных в каждой строке есть две кнопки "удалить" и "редактировать". Проблема заключается в том, что я без понятия как сделать чтобы при перезагрузки страницы эти строки не исчезали(знаю что есть session storage и local storage, но не знаю как это реализовать), при этом я хочу сохранить функционал кнопок удаления и редактирования. Очень буду благодраен помощи.
Вот html-код
<html dir="rtl" lang="he-IL">
<head>
<!-- Take from variable 'MyHead'-->
</head>
<body>
<header>
<!-- Take from variable 'MyHeader'-->
</header>
<div data-elementor-type="single-post" data-elementor-id="501"
class="elementor elementor-501 elementor-location-single post-357 page type-page status-publish hentry">
<section class='elementor-section elementor-top-section elementor-element'>
<div class="container">
<div class="menu">
</div>
<div class="wrapper-template">
<div class="template">
<form id="form">
<div class="date-input">
<label for="first-name">From:
<input type="text" id="From" name="From" placeholder="Mm/yyyy">
<p style="display: none; color: red;" id="errorFrom">Wrong date format </p>
</label>
<label for="last-name">To:
<input type="text" id="To" name="To" placeholder="Mm/yyyy">
<p style="display: none; color: red;" id="errorTo">Wrong date format </p>
</label>
</div>
<div class="type-select">
<label for="Academic-institution">Academic institution:
<select id="Academic-institution" name="Academic-institution">
</select>
</label>
<label for="Field-of-Study">Field of Study:
<select id="Field-of-Study" name="Field-of-Study">
</select>
</label>
<label for="Type">Type (MSc/BSc/…):
<select id="Type" name="Type">
</select>
</label>
</div>
<button type="submit">Save</button>
</form>
<div class="data-table">
<table id="table">
<thead>
<tr>
<th>From</th>
<th>To</th>
<th>Academic institution</th>
<th>Field of Study</th>
<th>Type</th>
<th style="border: none;"></th>
<th style="border: none;"></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
</section>
</div>
<footer>
<!-- Take from variable 'MyFooter'-->
</footer>
<script src="./js/script.js"></script>
<script src="./js/grid.js"></script>
</body>
</html>
javascripte код:
const form = document.getElementById('form')
const inputFrom = document.getElementById('From');
const inputTo = document.getElementById('To');
const errorMessageFrom = document.getElementById('errorFrom');
const errorMessageTo = document.getElementById('errorTo');
const inputValidation = (e) => {
const valueFrom = inputFrom.value;
const valueTo = inputTo.value;
const regex = /^(0[1-9]|1[0-2])\/[0-9]{4}$/;
if (e.target === inputFrom) {
if (regex.test(valueFrom)) {
errorMessageFrom.style.display = 'none';
}
else {
errorMessageFrom.style.display = 'block';
}
}
else if (e.target === inputTo) {
if (regex.test(valueTo)) {
errorMessageTo.style.display = 'none';
}
else {
errorMessageTo.style.display = 'block';
}
}
}
const processData = (data, id) => {
console.log('data:', data)
const select = document.getElementById(id);
console.log('id:', id)
if (select instanceof HTMLSelectElement) {
// Adding options to the select
for (const key in data) {
const option = document.createElement('option');
option.value = key;
option.text = data[key];
if (option instanceof Node) {
select.appendChild(option);
}
}
}
};
fetch('https://wbd.tlntq.com/web/webServices/getVars.php')
.then(response => response.json())
.then((data) => {
processData(data.EDUCATION_MOSAD, 'Academic-institution');
processData(data.EDUCTION_FIELD, 'Field-of-Study');
processData(data.EDUCATION_TYPE, 'Type');
});
form.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(form);
const data = {};
formData.forEach((value, key) => {
data[key] = value;
});
const tbody = document.querySelector('#table tbody');
const row = tbody.insertRow();
// Добавляем ячейки в строку
const fromCell = row.insertCell(0);
const toCell = row.insertCell(1);
const academicInstitutionCell = row.insertCell(2);
const fieldOfStudyCell = row.insertCell(3);
const typeCell = row.insertCell(4);
const deleteCell = row.insertCell(5);
const editCell = row.insertCell(6);
// Заполняем ячейки данными
fromCell.textContent = data.From;
toCell.textContent = data.To;
academicInstitutionCell.textContent = data['Academic-institution'];
fieldOfStudyCell.textContent = data['Field-of-Study'];
typeCell.textContent = data.Type;
//delete button
const deleteButton = document.createElement('button');
deleteButton.textContent = 'x';
deleteButton.addEventListener('click', () => {
row.remove();
});
deleteCell.appendChild(deleteButton);
//edit button
const editButton = document.createElement('button');
editButton.textContent = 'Edit';
editButton.addEventListener('click', () => {
editButton.style.display = 'none';
//create input
const inputFrom = document.createElement('input');
inputFrom.value = fromCell.textContent;
fromCell.textContent = '';
fromCell.appendChild(inputFrom);
const inputTo = document.createElement('input');
inputTo.value = toCell.textContent;
toCell.textContent = '';
toCell.appendChild(inputTo);
// create select
const selectAcademicInstitution = document.createElement('select');
selectAcademicInstitution.id = 'selectAcademicInstitution';
academicInstitutionCell.textContent = '';
academicInstitutionCell.appendChild(selectAcademicInstitution);
const selectFieldOfStudy = document.createElement('select');
selectFieldOfStudy.id = 'selectFieldOfStudy';
fieldOfStudyCell.textContent = '';
fieldOfStudyCell.appendChild(selectFieldOfStudy);
const selectType = document.createElement('select');
selectType.id = 'selectType';
typeCell.textContent = '';
typeCell.appendChild(selectType);
fetch('https://wbd.tlntq.com/web/webServices/getVars.php')
.then(response => response.json())
.then((data) => {
processData(data.EDUCATION_MOSAD, 'selectAcademicInstitution');
processData(data.EDUCTION_FIELD, 'selectFieldOfStudy');
processData(data.EDUCATION_TYPE, 'selectType');
});
//create savebutton
const saveButton = document.createElement('button');
saveButton.textContent = 'Save';
saveButton.addEventListener('click', () => {
fromCell.textContent = inputFrom.value;
toCell.textContent = inputTo.value;
academicInstitutionCell.textContent = selectAcademicInstitution.value;
fieldOfStudyCell.textContent = selectFieldOfStudy.value;
typeCell.textContent = selectType.value;
editCell.textContent = '';
editCell.appendChild(editButton);
saveButton.style.display = 'none';
editButton.style.display = 'block';
});
editCell.appendChild(saveButton);
})
editCell.appendChild(editButton);
console.log(data)
});
inputFrom.addEventListener('change', inputValidation);
inputTo.addEventListener('change', inputValidation);
Пытадся разобраться с localstorage, но не получилось