My HTML:
<body>
<form name="slectMovie">
IMDb rating:
<button type="submit" value="Select">Select</button>
</form>
<script src="script.js"></script>
</body>
My JS:
const getData = async () => {
try {
const res = await fetch("http://134.209.87.8:1337/api/movies");
const data = await res.json();
console.log(data);
const imdbSelect = document.createElement("select");
document.querySelector("form").append(imdbSelect);
if (data.data.length > 0) {
const IMDbRating = [
...new Set(data.data.map((x) => x.attributes.IMDbRating)),
];
IMDbRating.forEach((category) => {
const option = document.createElement("option");
option.textContent = category;
imdbSelect.append(option);
});
}
} catch (err) {
console.log(err);
}
};
getData();
I have one selection, that is movie rating, that I'm fetching from created API, and adding option values from API.
I would like to know how do I display items underneath form that are only selected in select tag.
For example if I chose first option, I would like to display items underneath form that only match that criteria, if I chose other option to display only itmes that have that option criteria.
CodePudding user response:
there are many ways to achieve this. below is one of these.
In The html, add new line to display the items.
<form name="slectMovie">
IMDb rating:
<button type="submit" value="Select">Select</button>
</form>
<ul id="theList"></ul>
<script src="script.js"></script>
in javascript add few lines for display functionality
let data = [];
function dispplayData({ target }) {
const selectedItem = data.data.filter(
(d) => d.attributes.IMDbRating === Number(target.value)
);
const displayList = document.querySelector("#theList");
displayList.innerHTML = "";
selectedItem.forEach((item) => {
let listItem = document.createElement("li");
listItem.textContent = item.attributes.title;
displayList.appendChild(listItem);
});
console.log(selectedItem);
}
const getData = async () => {
try {
const res = await fetch("http://134.209.87.8:1337/api/movies");
data = await res.json();
console.log(data);
const imdbSelect = document.createElement("select");
document.querySelector("form").append(imdbSelect);
imdbSelect.addEventListener("change", dispplayData);
if (data.data.length > 0) {
const IMDbRating = [
...new Set(data.data.map((x) => x.attributes.IMDbRating)),
];
IMDbRating.forEach((category) => {
const option = document.createElement("option");
option.textContent = category;
imdbSelect.append(option);
});
}
} catch (err) {
console.log(err);
}
};
getData();
Hope this helps you.