Сохранение изменений введённых данных в таблицу при обновлении страницы
Всем здравствуйте! Нужна помощь. Есть таблица, но при обновлении страницы, она обнуляется. Какой функцией можно это исправить? Пара моментов:
- Таблица должна обнуляться с началом следующих суток.
- Можно ли сохранять введённые данные в текстовом файле (или лучше не в .txt)?
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<style type="text/css"></style>
<title>КПП</title>
</head>
<h1>Журнал</h1>
<a href="pages/narad.html"><h2>Страница 2</h2></a>
<div id="current_date_time_block"></div>
<div id="current_date_time_block2"></div>
<body>
<table class="table">
<thead id="tableHeader"><!--ряд с ячейками заголовков-->
</thead>
<tbody id="tableBody"></tbody>
</table>
<button type="button" id="botton_add" onclick="addNewRow()">Добавить строку</button>
<button type="button" id="botton_save" onclick="saveTable()">Сохранить</button>
<script src="js/index.js"></script>
</body>
</html>
JavaScript
/* функция получения текущей даты и времени */
function zero_first_format(value) {
return (value < 10) ? value='0'+value : value;
}
function date_time(){
const current_datetime = new Date();
const day = zero_first_format(current_datetime.getDate());
const month = zero_first_format(current_datetime.getMonth()+1);
const year = current_datetime.getFullYear();
const hours = zero_first_format(current_datetime.getHours());
const minutes = zero_first_format(current_datetime.getMinutes());
const seconds = zero_first_format(current_datetime.getSeconds());
return `${day}.${month}.${year} ${hours}:${minutes}:${seconds}`;
}
/* выводим текущую дату и время */
setInterval(function () {
document.getElementById('current_date_time_block2').innerHTML = date_time();
}, 1000);
const tableHeader = document.getElementById('tableHeader');
const tableBody = document.getElementById('tableBody');
const NO_DATA = " ";
// блок данных
const jurnalRows = [
[1, , , , , , ]
]
const lastNames =[
NO_DATA,
"Иванов А.А.",
"Петров В.В.",
"Cидоров Д.Е."
];
const models =[
NO_DATA,
"Жигули о000оо",
"Волга ч000чч",
"Лада х000хх"
];
const columns = [
{name: "№ п/п", source:null, className:"number"},
{name: "Фамилия водителя", source:createSelect(lastNames), dataSource: lastNames, className: "lastName"},
{name: "Марка / № машины", source:createSelect(models), dataSource: models, className: "model"},
{name: "№ путевого листа", source:createInput('text'), dataSource: "", className:"listNumber"},
{name: "Время выезда", source:createInput('time'), dataSource: "time", className:"timeOut"},
{name: "Начальный километраж", source:createInput('number'), dataSource: 0, className: "begin"},
{name: "Конечный километраж", source:createInput('number'), dataSource: 0, className: "end"},
{name: "Время заезда", source:createInput('time'), dataSource: "time", className:"timeIn"},
{name: "Пройдено км", source:null, className: "sum"}
]
// конец блока данных
// блок переменных
let currentRow = -1;
let currentCol = -1;
let currentCell = null;
const indexOfSum = columns.indexOf(columns.find( e => e.className === "sum"));
const indexOfBegin = columns.indexOf(columns.find( e => e.className === "begin"));
const indexOfEnd = columns.indexOf(columns.find( e => e.className === "end"));
// конец блока переменных
// подсчет колонки "Пройдено км"
function calulate(event) {
const cell = event.target;
if (cell.parentNode.className === "begin") {
jurnalRows[currentRow][indexOfSum] = jurnalRows[currentRow][indexOfEnd] - cell.value;
} else if (cell.parentNode.className === "end") {
jurnalRows[currentRow][indexOfSum] = cell.value - jurnalRows[currentRow][indexOfBegin];
}
tableBody.children[currentRow].children[indexOfSum].textContent = jurnalRows[currentRow][indexOfSum]
}
function createInput(type) {
const input = document.createElement('input');
input.setAttribute('type', type);
input.addEventListener('change', calulate, false);
return input;
}
function createSelect(list) {
const select = document.createElement('select');
select.cla
for (let i = 0; i < list.length; i++){
const option = document.createElement('option');
option.value=i;
option.textContent=list[i];
select.appendChild(option);
}
return select;
}
const createCell = (text, className) => {
const cell = document.createElement('td');
cell.textContent=text
if(className) cell.className = className;
return cell;
}
const createHeader = () => {
const row = document.createDocumentFragment();
for (i = 0; i< columns.length; i++){
const cell = createCell(columns[i].name, columns[i].className);
row.appendChild(cell);
}
return row;
}
const createRow = (rowData) => {
const row = document.createElement('tr');
for (i = 0; i< columns.length; i++){
const cell= createCell(rowData[i], columns[i].className);
row.appendChild(cell);
}
return row
}
function addNewRow() {
const rowData = [jurnalRows.length +1, ...Array(columns.length-1).fill(NO_DATA)];
jurnalRows.push(rowData)
tableBody.appendChild(createRow(rowData))
}
function addRow(rowData) {
tableBody.appendChild(createRow(rowData))
}
const fillTable = () => {
tableHeader.appendChild(createHeader())
for (let i = 0; i < jurnalRows.length; i++){
addRow(jurnalRows[i])
}
//addNewRow()
}
fillTable()
const showEditField = () => {
if (event.target.tagName !== 'TD') return;
const cell = event.target;
const column = columns.find(e => e.className === cell.className);
const index = columns.indexOf(column);
// запоминаем последний выбор в данных
if (currentCell && currentCol !== -1 && currentRow !== -1){
if (Array.isArray(columns[currentCol].dataSource)){
jurnalRows[currentRow][currentCol] = columns[currentCol].dataSource[+columns[currentCol].source.value];
currentCell.textContent = jurnalRows[currentRow][currentCol];
} else {
jurnalRows[currentRow][currentCol] = columns[currentCol].source.value;
currentCell.textContent = jurnalRows[currentRow][currentCol];
}
}
// переносим ячейку выбора
if (column.source) {
oldData = cell.innerHTML;
cell.innerHTML = "";
if (Array.isArray(column.dataSource)){
column.source.value = `${column.dataSource.indexOf(oldData)}`;
} else {
column.source.value = oldData !== NO_DATA ? oldData : column.dataSource;
}
cell.appendChild(column.source)
currentCol = index;
currentRow = Array.prototype.indexOf.call(tableBody.children, cell.parentNode);
currentCell = cell;
// console.table(jurnalRows);
}
}
tableBody.addEventListener('click',showEditField, false)