I want to add the name of the cat to the drop-down menu. I can access properties and their values. But, when I try to enter/put those values in the menu, only the last value is getting store. I am assuming that it is (code - Function accessArray) replacing the current value once it loops through the whole thing. console.log(data)
data.name has the list of the cat names. console.log(element.name)
I want to create a list so that I can have names of all the cats in the drop-down menu. drop-down
Here is the link of public API that I am using - https://docs.thecatapi.com/api-reference/breeds/breeds-list
async function start(){
try{
const response = await fetch("https://api.thecatapi.com/v1/breeds");
const data = await response.json();
console.log (data);
filterData(data);
}catch (e){
console.log("Error : "+ e);
}
}
start();
function filterData (data){
data.forEach(element => {
console.log(element.name);
acessArray(element.name);
});
}
function acessArray(data){
document.getElementById("catList").innerHTML = `
<select>
<option value="Choose a cat">Choose a cat</option>
<option> ${data} </option>
</select>
`;
}
Not sure what you want your code do but if it just <option> then you will figure it out.
Each time you are set this
document.getElementById("catList").innerHTML = '<select>...</select>'
you overwrite the last input.
Look the code and replace what you need. ๐
async function start(){
try{
const response = await fetch("https://api.thecatapi.com/v1/breeds");
const data = await response.json();
console.log (data);
filterData(data);
}catch (e){
console.log("Error : "+ e);
}
}
start();
function filterData (data){
document.getElementById("catList").innerHTML = ''; // clear the list
data.forEach(element => {
console.log(element.name);
acessArray(element.name);
});
}
function acessArray(data){
// This will add a <select> over another <select> and so on
document.getElementById("catList").innerHTML += `
<select>
<option value="Choose a cat">Choose a cat</option>
<option> ${data} </option>
</select>
`;
}
What I think it should do:
async function start(){
try{
const response = await fetch("https://api.thecatapi.com/v1/breeds");
const data = await response.json();
console.log (data);
filterData(data);
}catch (e){
console.log("Error : "+ e);
}
}
start();
function filterData (data){
document.getElementById("catList").innerHTML = `
<select>
<option value="Choose a cat">Choose a cat</option>
`; // clear the list and start filling
data.forEach(element => {
console.log(element.name);
acessArray(element.name);
});
document.getElementById("catList").innerHTML += '</select>'; //End
}
function acessArray(data){
// This will add a <select> over another <select> and so on
document.getElementById("catList").innerHTML += `
<option> ${data} </option>
`;
}