Witam
Od paru godzin zmagam się z problemem w jaki sposób mogę dodać nowy rekord do tablicy obiektów aczkolwiek pomiędzy rekordami używając do tego funkcji slice. Wydaje mi się, że wszystko dobrze wygąda aczkolwiek utknąłem na zamianie tablicy z nowej na starą aby ją wyświetlić. Nie jestem pewien gdzie popełniłem błąd.
Chyba, że w tym problemie idę nie tym tropem co trzeba.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript CRUD Example</title>
</head>
<body>
<h1>JavaScript CRUD Example</h1>
<form id="addItemForm">
<label for="itemName">Name:</label>
<input type="text" id="itemName" required>
<label for="itemDescription">Description:</label>
<input type="text" id="itemDescription" required>
<button type="submit" onclick="showAllItems()">Add Item</button>
</form>
<div id="itemList">
<!-- Existing items will be displayed here -->
</div>
</body>
<script>
//const numbers = [1, 2, 4, 5
let dataToProcess = [
{ id: 123, name: "Gary", position: "Office worker" },
{ id: 234, name: "Marry", position: "Manager" },
{ id: 345, name: "Shon", position: "Sales specialist" }
];
const index = 2;
function addRecordInSpecIndex(name, position){
const newRecord = {
id : dataToProcess.length + 1,
name : name,
position : position
};
const newNumbers = [
...dataToProcess.slice(0, index),
newRecord,
...dataToProcess.slice(index)
];
dataToProcess.splice(0, newNumbers);
//Podmiana tablicy
showAllItems();
}
function showAllItems(){
const name = document.getElementById("itemName").value;
const position = document.getElementById("itemDescription").value;
let listOfItems = "";
dataToProcess.forEach( itm => {
listOfItems += `<div>
<p><strong>${itm.name}</strong>: ${itm.position}</p>
</div>`;
});
document.getElementById("itemList").innerHTML = listOfItems;
}
showAllItems();
function executeProcess(){
document.getElementById("addItemForm").addEventListener("submit", function(ev) {
ev.preventDefault(); // Prevent default form submission
const name = document.getElementById("itemName").value;
const position = document.getElementById("itemDescription").value;
addRecordInSpecIndex(name, position);
});
}
</script>
</html>