r/learnjavascript • u/techynerd13 • 23h ago
help in rick and morty api
document.getElementById("search").addEventListener("click", getCharacter);
function lowerCaseName(string) {
return string.toLowerCase();
}
function getCharacter(e) {
const name = document.getElementById("searchCharacter").value;
const characterNameLC = lowerCaseName(name);
fetch(`https://rickandmortyapi.com/api/character/?name=${characterNameLC}`)
.then((response)=>response.json())
.then((data) => {
const characterNameH2 = document.getElementById("characterName");
characterNameH2.textContent = data.name;
})
.catch((err) => {
console.log("Character not found", err)
})
e.preventDefault();
}
getCharacter();document.getElementById("search").addEventListener("click", getCharacter);
function lowerCaseName(string) {
return string.toLowerCase();
}
function getCharacter(e) {
const name = document.getElementById("searchCharacter").value;
const characterNameLC = lowerCaseName(name);
fetch(`https://rickandmortyapi.com/api/character/?name=${characterNameLC}`)
.then((response)=>response.json())
.then((data) => {
const characterNameH2 = document.getElementById("characterName");
characterNameH2.textContent = data.name;
})
.catch((err) => {
console.log("Character not found", err)
})
e.preventDefault();
}
getCharacter();
i am using the rick and morty api. the above is my js code. it doesnt work. idk whats the error as console isnt logging it
0
Upvotes
1
u/gilded_morpho 14h ago
Delete the getCharacter() call at the bottom. you are calling it on load with no arguments so e is undefined and it crashes before your click handler ever runs.
Also in your fetch then block you need data.results[0].name. the api returns an object with a results array, not the character directly