JavaScript how to change input value using public API and pure JavaScript - javascript

Could anyone explain to me why I cannot update my input value after clicking my submit button? My goal is to write a number, click the submit button and find the Pokémon with that number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<div class="pokemon"></div>
<button id="btn" onclick="testFunc(inputValue)">SUBMIT</button>
<input type="text" value="" id="myInput">
<script>
const btn = document.getElementById("btn");
const input = document.getElementById("myInput");
let inputValue = input.value;
const testFunc = function(a) {
const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: a,
}
const { url, type, id } = apiData
const apiUrl = `${url}${type}/${id}`
fetch(apiUrl)
.then((data) => {
if (data.ok) {
return data.json()
}
throw new Error('Response not ok.');
})
.then(pokemon => generateHtml(pokemon))
.catch(error => console.error('Error:', error))
const generateHtml = (data) => {
console.log(data)
const html = `
<div class="name">${data.name}</div>
<img src=${data.sprites.front_default}>
<div class="details">
<span>Height: ${data.height}</span>
<span>Weight: ${data.weight}</span>
</div>
`
const pokemonDiv = document.querySelector('.pokemon')
pokemonDiv.innerHTML = html
}
}
</script>
</body>
</html>
I will be grateful for any advice.
Best regards

You need to move the inputValue retrieval inside the testFunc function.
const testFunc = function() {
let inputValue = input.value;
const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: inputValue,
}
The button's onclick only knows about itself, it cannot reference input.
const btn = document.getElementById("btn");
const input = document.getElementById("myInput");
const testFunc = function() {
let inputValue = input.value;
const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: inputValue,
}
const { url, type, id } = apiData
const apiUrl = `${url}${type}/${id}`
fetch(apiUrl)
.then((data) => {
if (data.ok) {
return data.json()
}
throw new Error('Response not ok.');
})
.then(pokemon => generateHtml(pokemon))
.catch(error => console.error('Error:', error))
const generateHtml = (data) => {
//console.log(data) <-- Slows down the result
const html = `
<div class="name">${data.name}</div>
<img src=${data.sprites.front_default}>
<div class="details">
<span>Height: ${data.height}</span>
<span>Weight: ${data.weight}</span>
</div>
`
const pokemonDiv = document.querySelector('.pokemon')
pokemonDiv.innerHTML = html
}
}
<div class="pokemon"></div>
<button id="btn" onclick="testFunc()">SUBMIT</button>
<input type="text" value="25" id="myInput"> <!-- Default to Pikachu -->

Related

The github profile API data is undefined in JavaScript

I already check again on this code, but still couldn't figure it out why it won't work. So that I manage to make this web app using GitHub API.
but when I tried to search some data by their name, it turns out 'undefined' for everything that I was trying to find, like name, image, bio and etc.
My html code:
<html>
<head>
<title>Github Profile!</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
</head>
<body>
<form id="form">
<input type="text"
id="search"
placeholder="Search a User Here" />
</form>
<main id="main"></main>
<script src="script.js" defer></script>
</body>
</html>
Javascript:
const APIURL = 'https://api.github.com/users';
const main = document.getElementById('main');
const form = document.getElementById('form');
const search = document.getElementById('search');
async function getUser(user) {
const resp = await fetch(APIURL + user );
const respData = await resp.json();
createUserCard(respData);
}
function createUserCard(user) {
const cardHTML = `
<div class="card">
<div>
<img src="${user.avatar_url}"
alt="${user.name}" />
</div>
<div>
<h2>${user.name}</h2>
<p>${user.bio}</p>
<ul>
<li>${user.followers}</li>
<li>${user.following}</li>
<li>${user.public_repos}</li>
</ul>
</div>
</div>
`;
main.innerHTML = cardHTML;
}
form.addEventListener('submit', (e) => {
e.preventDefault();
const user = search.value;
if (user) {
getUser(user);
search.value = "";
}
});
I don't know what actually went wrong here.
Looks like you were just using the wrong URL.
const APIURL = 'https://api.github.com/users'; // no end slash
async function getUser(user) {
const resp = await fetch(APIURL + user );
so what you're doing here is calling the URL
https://api.github.com/usersusername
so you just need to add a slash in the APIURL variable.
const APIURL = 'https://api.github.com/users/';
const main = document.getElementById('main');
const form = document.getElementById('form');
const search = document.getElementById('search');
async function getUser(user) {
const resp = await fetch(APIURL + user);
console.log(resp)
const respData = await resp.json();
console.log(respData)
createUserCard(respData);
}
function createUserCard(user) {
const cardHTML = `
<div class="card">
<div>
<img src="${user.avatar_url}"
alt="${user.name}" />
</div>
<div>
<h2>${user.name}</h2>
<p>${user.bio}</p>
<ul>
<li>${user.followers}</li>
<li>${user.following}</li>
<li>${user.public_repos}</li>
</ul>
</div>
</div>
`;
main.innerHTML = cardHTML;
}
form.addEventListener('submit', (e) => {
e.preventDefault();
const user = search.value;
if (user) {
getUser(user);
search.value = "";
}
});
<html>
<head>
<title>Github Profile!</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
</head>
<body>
<form id="form">
<input type="text" id="search" placeholder="Search a User Here" />
</form>
<main id="main"></main>
<script src="script.js" defer></script>
</body>
</html>
Just add / after the users.
Your Code:
const APIURL = 'https://api.github.com/users';
async function getUser(user) {
const resp = await fetch(APIURL + user );
const respData = await resp.json();
createUserCard(respData);
}
Working Code:
const APIURL = 'https://api.github.com/users/';
async function getUser(user) {
const resp = await fetch(APIURL + user );
const respData = await resp.json();
createUserCard(respData);
}
This will get you the correct URL for the user
https://api.github.com/users/thesumitshrestha

Multiple fetches with eventListener

Hello there I am struggling to find the solution of this 'bug'. I am not even sure why its happening? Using Giphy API the goal is to upload gif then save the id from response to the localStorage.The initial upload seem to work fine, however each next upload does a multiple fetches and adds in the localStorage more than one id for each gif. Will really appreciate any advice. Thanks!
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form>
<input type="file" />
<input type="submit" />
</form>
<div class="tree"></div>
<script src="./fetch-api.js"></script>
</body>
</html>
JavaScript:
const form = document.querySelector('form');
const inputFlie = document.querySelector('input');
const preview = document.querySelector('.tree');
const apiKey = 'yourapikeyhere'
form.addEventListener('change', () => {
const uploadFile = new FormData();
uploadFile.append('file', inputFlie.files[0]);
const heads = {
method: 'POST',
api_key: apiKey ,
body: uploadFile,
};
form.addEventListener('submit', async (event) => {
event.preventDefault();
try {
const send = await fetch(
`https://upload.giphy.com/v1/gifs?api_key=${apiKey}`,
heads
);
const feedback = await send.json();
if (feedback.meta.status === 200) {
form.reset();
uploadID = feedback.data.id;
}
if (localStorage.getItem('uploaded') === null) {
//if we don't create an empty array
uploadedGifs = [];
uploadedGifs.push(uploadID);
localStorage.setItem('uploaded', JSON.stringify(uploadedGifs));
} else {
const currentItems = JSON.parse(localStorage.getItem('uploaded'));
currentItems.push(uploadID);
localStorage.setItem('uploaded', JSON.stringify(currentItems));
}
console.log(feedback);
} catch (error) {
console.log(error);
statusMesage.textContent = 'Something went wrong!';
}
});
});
separate event listeners, so as not to create a new one every time the form has been changed.
const form = document.querySelector('form');
const inputFlie = document.querySelector('input');
const preview = document.querySelector('.tree');
const apiKey = 'yourapikeyhere'
const heads = {
method: 'POST',
api_key: apiKey,
body: null,
};
form.addEventListener('change', () => {
const uploadFile = new FormData();
uploadFile.append('file', inputFlie.files[0]);
heads.body = uploadFile;
});
form.addEventListener('submit', async (event) => {
event.preventDefault();
try {
const send = await fetch(
`https://upload.giphy.com/v1/gifs?api_key=${apiKey}`,
heads
);
const feedback = await send.json();
if (feedback.meta.status === 200) {
form.reset();
uploadID = feedback.data.id;
}
if (localStorage.getItem('uploaded') === null) {
//if we don't create an empty array
uploadedGifs = [];
uploadedGifs.push(uploadID);
localStorage.setItem('uploaded', JSON.stringify(uploadedGifs));
} else {
const currentItems = JSON.parse(localStorage.getItem('uploaded'));
currentItems.push(uploadID);
localStorage.setItem('uploaded', JSON.stringify(currentItems));
}
console.log(feedback);
} catch (error) {
console.log(error);
statusMesage.textContent = 'Something went wrong!';
}
});

Could someone tell me what I did wrong in displaying data from fetching api to my html page in the Hackers News?

I am training on the Hacker News API project and I wanted to do it my way, I fetched the API with the following urls and I put a toggle_button function but when I try to put the variable data in this function nothing is displayed I do not know what is the problem can someone guide me?
Here's my HTML CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<title>ClonerNews</title>
</head>
<body>
<h2>Welcome To <span>ClonerNews</span> !</h2>
<div id="main">
<button id="liveData" class="category" onclick="toggleButton('liveData');">Live Data</button>
<button id="topstories" class="category" onclick="toggleButton('topstories');">Top Stories</button>
<button id="stories" class="category" onclick="toggleButton('stories');">Stories</button>
<button id="jobs" class="category" onclick="toggleButton('jobs');">Jobs</button>
<button id="polls" class="category" onclick="toggleButton('polls');">Polls</button>
</div>
<div id="result"></div>
<span id="span_txt" style="color: aliceblue;"></span>
</body>
<script src="script.js"></script>
</html>
And here's my script.js
//url of news api
var topStoriesUrl = "https://hacker-news.firebaseio.com/v0/topstories.json";
//url of particular news item
var newItemUrl = "https://hacker-news.firebaseio.com/v0/item/";
let result = document.getElementById("result"); seront affichées.
//fetch data
const fetchData = (url) => {
return new Promise((resolve, reject) => {
fetch(url)
.then((res) => res.json())
.then((data) => resolve(data))
.catch((err) => reject(err));
});
};
//show data
const showData = async () => {
var data = await fetchData(topStoriesUrl);
console.log(data);
data.map(async (d) => {
let newsData = await fetchData(`${newItemUrl}${d}.
json`);
console.log(newsData);
});
};
showData();
const liveData = getElementById("liveData");
const stories = getElementById("stories");
const jobs = getElementById("jobs");
const polls = getElementById("polls");
function toggleButton() {
var span = document.getElementById("span_txt");
if(span.innerHTML != "") {
span.innerHTML = "";
} else {
span.innerHTML = data
}
}

adding an event listener to my javascript that needs to use my dropdrown values to sort the list of dog breeds

//console.log('%c HI', 'color: firebrick')
document.addEventListener('DOMContentLoaded', () => {
ceo(),
breeds()
})
function ceo() {
const imgUrl = "https://dog.ceo/api/breeds/image/random/4"
fetch(imgUrl)
.then(resp => resp.json())
.then(json => renderImages(json))
}
function renderImages(images) {
images.message.forEach(renderImage);
}
function renderImage(urlImg){
const loc = document.getElementById('dog-image-container')
//console.log(urlImg)
const img = document.createElement('img')
//console.dir(img)
img.className = "dog-image"
img.height = 300
img.src = urlImg
loc.appendChild(img)
}
function breeds() {
const breedUrl = 'https://dog.ceo/api/breeds/list/all'
fetch(breedUrl)
.then(resp => resp.json())
.then(json => breed(json))
}
function breed(dog) {
const doggo = Object.keys(dog.message)
doggo.forEach(element => breedList(element))
//dog.message.forEach(dog => dog.breedList);
}
function breedList(dogBreeds) {
const ul = document.getElementById('dog-breeds')
const li = document.createElement('li')
li.innerText = dogBreeds
ul.appendChild(li)
ul.addEventListener('click', event => {
if(event.target.matches('li')) {
event.target.style.color = 'blue'
}
})
// the source of my pain
const dropdownLetter = document.querySelector("#breed-dropdown")
dropdownLetter.addEventListener('change', event => {
let dogs = []
const letter = event.target.value
const dogsList = dogs.filter(dogs => {
return dogs.startsWith(letter)
},
)
})
}
dogs filter is returning not a function when i enter anything and as it is now dogs is undefined. i need help invoking the correct array then print the captured results to the HTML AAAAGGGGAHHHHH I can post the html too . my problem starts where it says the source of my pain. ignore that part basically i just need to sort my array using the dropdown values
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Intro to AJAX Practice Tasks</title>
<script src="src/index.js" charset="utf-8"></script>
</head>
<body>
<h1>Dog CEO</h1>
<div id="dog-image-container">
<!-- images here -->
</div>
<hr>
<label for="select-breed">Filter Breeds That Start with:</label>
<select id="breed-dropdown" name="select-breed">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
<ul id="dog-breeds">
</ul>
</body>
</html>
Save the dogs data in breeds function. (declare global variable)
Use dogs to filter in change listener
check the snipper
dropdownLetter.addEventListener("change", (event) => {
const letter = event.target.value;
const dogsList = dogs.filter((dog) => {
return dog.startsWith(letter);
});
const ul = document.getElementById("dog-breeds");
ul.innerHTML = '';
dogsList.forEach((element) => breedList(element));
});
let dogs;
document.addEventListener("DOMContentLoaded", () => {
ceo(), breeds();
});
function ceo() {
const imgUrl = "https://dog.ceo/api/breeds/image/random/4";
fetch(imgUrl)
.then((resp) => resp.json())
.then((json) => renderImages(json));
}
function renderImages(images) {
images.message.forEach(renderImage);
}
function renderImage(urlImg) {
const loc = document.getElementById("dog-image-container");
//console.log(urlImg)
const img = document.createElement("img");
//console.dir(img)
img.className = "dog-image";
img.height = 300;
img.src = urlImg;
loc.appendChild(img);
}
function breeds() {
const breedUrl = "https://dog.ceo/api/breeds/list/all";
fetch(breedUrl)
.then((resp) => resp.json())
.then((json) => breed(json));
}
function breed(dog) {
const doggo = Object.keys(dog.message);
// save dogs data
dogs = doggo;
doggo.forEach((element) => breedList(element));
//dog.message.forEach(dog => dog.breedList);
}
function breedList(dogBreeds) {
const ul = document.getElementById("dog-breeds");
const li = document.createElement("li");
li.innerText = dogBreeds;
ul.appendChild(li);
ul.addEventListener("click", (event) => {
if (event.target.matches("li")) {
event.target.style.color = "blue";
}
});
}
// the source of my pain
const dropdownLetter = document.querySelector("#breed-dropdown");
dropdownLetter.addEventListener("change", (event) => {
const letter = event.target.value;
const dogsList = dogs.filter((dog) => {
return dog.startsWith(letter);
});
const ul = document.getElementById("dog-breeds");
ul.innerHTML = '';
dogsList.forEach((element) => breedList(element));
});
<h1>Dog CEO</h1>
<div id="dog-image-container">
<!-- images here -->
</div>
<hr>
<label for="select-breed">Filter Breeds That Start with:</label>
<select id="breed-dropdown" name="select-breed">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
<ul id="dog-breeds">
</ul>

My AddEventListener function is not working in any browser. How can this be solved?

Here is my JS code:
const BASE_URL = "http://localhost:3000";
const CATEGORIES_URL = `${BASE_URL}/categories`;
const ITEMS_URL = `${BASE_URL}/items`;
window.addEventListener("load", () => {
getCategories();
createNewCategory();
});
const main = () => {
return document.querySelector("main");
};
//loads all the categories
const getCategories = () => {
fetch("http://localhost:3000/categories")
.then((response) => response.json())
.then((data) => renderCategories(data));
};
const renderCategories = (categoriesData) => {
categoriesData.forEach((category) => renderCategoriesCard(category));
};
const renderCategoriesCard = (categories) => {
let categoriesCard = document.createElement("div");
categoriesCard.className = "card";
categoriesCard.dataset.id = categories.id;
categoriesCard.innerHTML = `
<p>${categories.name}</p>
<button data-category-id=${categories.id}>Add Item</button>
`;
categoriesCard.lastElementChild.addEventListener("click", displayItemForm);
main().appendChild(categoriesCard);
let itemsList = document.createElement("ul");
itemsList.setAttribute("class", "items-list");
itemsList.dataset.id = categories.id;
categoriesCard.appendChild(itemsList);
categories.items.forEach((item) => renderItems(item, itemsList));
};
const createNewCategory = () => {
let form = document.querySelector("a");
form.addEventListener("click", displayCategoryForm);
};
const displayCategoryForm = () => {
let categoryForm = document.getElementById("category-form");
let html = `
<form>
<label>Name</label>
<input type="text" id="name">
<input type="submit" value="Submit">
</form>
`;
categoryForm.innerHTML = html;
document.querySelector("form").addEventListener("submit", createCategory);
};
const createCategory = () => {
event.preventDefault();
console.log("Form clicked");
const category = {
name: document.getElementById("name").value,
};
//createNewCategory();
//fetch POST
fetch(CATEGORIES_URL, {
method: "POST",
body: JSON.stringify(category),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
})
.then((response) => response.json())
.then((data) => {
renderCategoriesCard(data);
clearCategoryForm();
});
};
const renderItems = (item, list) => {
let itemCard = document.createElement("li");
itemCard.id = `item-${item.id}`;
itemCard.innerText = `Title: ${item.title}`;
let releaseBtn = document.createElement("button");
releaseBtn.className = "delete";
releaseBtn.dataset.itemId = item.id;
releaseBtn.innerText = "Delete";
releaseBtn.addEventListener("click", deleteItem);
ItemCard.appendChild(releaseBtn);
if (!list) {
list = event.target.parentElement.lastElementChild;
}
list.appendChild(itemCard);
};
const clearForm = () => {
let item = document.getElementById("item-form");
item.innerHTML = "";
};
const clearCategoryForm = () => {
let category = document.getElementById("category-form");
category.innerHTML = "";
};
const deleteItem = () => {
fetch(ITEMS_URL + `/${event.target.dataset.ItemId}`, {
method: "DELETE",
}).then(removeItem(event.target.dataset.itemId));
};
const removeItem = (id) => {
let cardToRemove = document.getElementById(`item-${id}`);
cardToRemove.parentElement.removeChild(cardToRemove);
};
const displayItemForm = () => {
let itemForm = document.getElementById("item-form");
let html = `
<form data-category-id="${event.target.dataset.categoryId}">
<label>Title</label>
<input type="text" id="title">
<label>Item Quantity</label>
<input type="text" id="body">
<input type="submit" value"Submit">
</form>
`;
itemForm.innerHTML = html;
document.querySelector("form").addEventListener("submit", createItem);
};
const createItem = () => {
event.preventDefault();
console.log("adding items...");
let categoryCardId = event.target.dataset.categoryId;
console.log(categoryCardId);
const item = {
title: document.getElementById("title").value,
quantity: document.getElementById("quantity").value,
category_id: categoryCardId,
};
//createItem();
console.log(item);
fetch(ITEMS_URL, {
method: "POST",
body: JSON.stringify(item),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
})
.then((response) => response.json())
.then((data) => {
let item = new Item(data);
item.renderItem();
clearForm();
});
};
<!DOCTYPE html>
<html>
<head>
<title>Groceries</title>
<link rel="stylesheet" href="index.css">
<script src= "src/index.js"></script>
<script src= "src/item.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Red+Rose:wght#300&display=swap" rel="stylesheet">
</head>
<body>
<h1>Groceries</h1>
<a id="categoryForm" href="#">Add New Category</a>
<div id="category-form"></div>
<main id="category-container">
<div id="item-form"></div>
</main>
</body>
</html>
I've tried so many things and this just doesnt seem to work. I cannot click the link, nothing happens in any browser.
Nothing seems to work passed the "Create new Category" part. I'm not sure why Im not able to add a new item. When I hit "submit" on adding an item, the program pauses at "adding item..." and then gives an error. Any help would be greatly appreciated.
Two things in your code
Need to invoke the createNewCategory
addEventListener("submit", createCategory) Either you missed this function in the question, for now added a simple function
Check the below snippet
const createNewCategory = () => {
let form = document.querySelector("a");
form.addEventListener("click", displayCategoryForm);
};
const displayCategoryForm = () => {
let categoryForm = document.getElementById("category-form");
let html = `
<form>
<label>Name</label>
<input type="text" id="name">
<input type="submit" value="Submit">
</form>
`;
categoryForm.innerHTML = html;
document.querySelector("form").addEventListener("submit", createCategory);
};
createNewCategory()
const createCategory = () => alert('i am createCategroy function')
<a id="categoryForm" href="#">Add New Category</a>
<div id="category-form"></div>

Categories

Resources