I'm a beginner in JavaScript, and I'm trying to filter an array of vehicles, using dropdown menus, the first filter shows it by brand name, then the second filter by type of vehicle. Filters seem to work just fine but when I select a brand and then a type it shows me all the array of items using the type filter, and ignores the brand filter
Array:
const Data = [
{
brand: "Volkswagen",
type: "Car",
model: "Golf",
year: "2019",
price: "$12,000",
},
{
brand: "Volkswagen",
type: "Truck",
model: "Tiguan",
year: "2020",
price: "$20,000",
},
{
brand: "Mazda",
type: "Car",
model: "Mazda 3",
year: "2022",
price: "$32,000",
},
{
brand: "Mazda",
type: "Truck",
model: "Mazda 6",
year: "2021",
price: "$29,000",
},
{
brand: "Tesla",
type: "Car",
model: "Model S",
year: "2023",
price: "$42,000",
},
{
brand: "Tesla",
type: "Truck",
model: "Model X",
year: "2020",
price: "$50,000",
},
];
Functions:
const getSelectedValue = () => {
let brandSelection = document.getElementById("brandDropdown").value;
let selection = document.getElementById("dropDownSelection");
// show all cars
if (brandSelection === "All") {
selection.innerHTML = "";
Data.forEach((car) => {
selection.innerHTML += `<div class="car">
<h3>${car.brand}</h3>
<p>${car.type}</p>
<p>${car.model}</p>
<p>${car.year}</p>
<p>${car.price}</p>
</div>`;
});
}
// show selected brand
else {
selection.innerHTML = "";
Data.forEach((car) => {
if (car.brand === brandSelection) {
selection.innerHTML += `<div class="car">
<h3>${car.brand}</h3>
<p>${car.type}</p>
<p>${car.model}</p>
<p>${car.year}</p>
<p>${car.price}</p>
</div>`;
}
});
}
console.log(brandSelection);
};
// filter by type when brand is selected
const getSelectedType = () => {
let typeSelection = document.getElementById("typeDropdown").value;
let selection = document.getElementById("dropDownSelection");
// show all cars
if (typeSelection === "All") {
selection.innerHTML = "";
Data.forEach((car) => {
selection.innerHTML += `<div class="car">
<h3>${car.brand}</h3>
<p>${car.type}</p>
<p>${car.model}</p>
<p>${car.year}</p>
<p>${car.price}</p>
</div>`;
});
}
// show selected type
else {
selection.innerHTML = "";
Data.forEach((car) => {
if (car.type === typeSelection) {
selection.innerHTML += `<div class="car">
<h3>${car.brand}</h3>
<p>${car.type}</p>
<p>${car.model}</p>
<p>${car.year}</p>
<p>${car.price}</p>
</div>`;
}
});
}
console.log(typeSelection);
};
HTML:
<body>
<div class="dropDown">
<div class="Brand">
<select name="" id="brandDropdown" onchange="getSelectedValue()">
<option value="All">All</option>
<option value="Volkswagen">Volkswagen</option>
<option value="Mazda">Mazda</option>
<option value="Tesla">Tesla</option>
</select>
</div>
<div class="Type">
<select name="" id="typeDropdown" onchange="getSelectedType()">
<option value="">Type</option>
<option value="All">All</option>
<option value="Car">Car</option>
<option value="Truck">Truck</option>
</select>
</div>
</div>
<div class="" id="dropDownSelection">
</div>
</body>