Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
83 lines (81 loc) · 2.88 KB
/
Copy pathscript.js
File metadata and controls
83 lines (81 loc) · 2.88 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
document.addEventListener('DOMContentLoaded', () => {
const loadCarsBtn = document.getElementById('loadCarsBtn');
const carList = document.getElementById('carList');
cars = [];
loadCarsBtn.addEventListener('click', () => {
fetch('http://localhost:3001/cars')
.then(response => response.json())
.then(data => {
cars = data;
carList.innerHTML = '';
data.forEach((car, index) => {
const carCard = document.createElement('div');
carCard.classList.add('car-card');
carCard.innerHTML = `
<h2>${car.make} ${car.model}</h2>
<p><strong>Year:</strong> ${car.year}</p>
<p><strong>Make:</strong> ${car.make}</p>
<p><strong>Model:</strong> ${car.model}</p>
<p><strong>Price:</strong> R${car.price}</p>
<button class="btn btn-remove" data-index="${index}">Remove</button>
`;
carList.appendChild(carCard);
});
})
.catch(error => {
console.error('Error fetching car data:', error);
});
});
});
function addCar(newCar) {
fetch('http://localhost:3001/cars', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newCar)
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
//reload cars
// const loadCarsBtn = document.getElementById('loadCarsBtn');
loadCarsBtn.click();
})
.catch(error => {
console.error('Error:', error);
});
}
carForm.addEventListener('submit', event => {
event.preventDefault();
const make = document.getElementById('make').value;
const model = document.getElementById('model').value;
const year = document.getElementById('year').value;
const price = document.getElementById('price').value;
addCar({ make, model, year, price });
carForm.reset();
});
// Function to remove a car
function removeCar(index) {
const carId = cars[index].id;
fetch(`http://localhost:3001/cars/${carId}`, {
method: 'DELETE'
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
//reload cars
// const loadCarsBtn = document.getElementById('loadCarsBtn');
loadCarsBtn.click();
})
.catch(error => {
console.error('Error:', error);
});
}
// Event delegation for remove buttons
carList.addEventListener('click', event => {
if (event.target.classList.contains('btn-remove')) {
const index = event.target.dataset.index;
removeCar(index);
}
});