I'm really new to javascript.
I'm trying to setup a page that fetches from a placeholder API(https://jsonplaceholder.typicode.com/posts) and displays the Title, Author(which I had to add) as well as the Body. I'm also trying to give the ability to use the search bar to filter the results by userId.
I got some help a few days ago getting the data from the API to show on my page but I've been struggling to get the search bar to work. Doe's anyone have any ideas on how to get it to work?
Any help is greatly appreciated.
const searchBar = document.getElementById('search');
const filterPost = document.getElementById('post');
Promise.all([1, 22, 33, 44, 55, 66, 77, 88, 95, 99].map(id =>
fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method:'PATCH',
body: JSON.stringify({
name: "John Doe",
}),
headers: {
'Content-Type': 'application/json; charset=UTF-8'
},
})
.then((response) => response.json())))
.then(data => {
console.log(data);
const html = data.map(posts => {
return `
<div class="post">
<p id="title">${posts.title}</p>
<p id="author">${posts.name}</p>
<p id="body">${posts.body}</p>
</div>`
}).join(' ');
console.log(html);
document.querySelector('#content').insertAdjacentHTML('beforeend', html);
});
//filter by userId
searchBar.addEventListener('input', (event) => {
console.log("user typed:", event.target.value)
filterPost = data.posts.filter(posts => posts.userId.includes(event.target.value))
}).join(' ');
console.log(filterPost);
document.querySelector('#content').insertAdjacentHTML('beforeend', filterPost);
!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="resources/css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<title>Code Problem 4</title>
</head>
<body>
<header><h1>Blog Post</h1></header>
<div id="content">
<h2>Posts</h2>
<form id="search" action="action_page.php">
<input type="text" placeholder="Filter by User ID" name="search">
<button type="submit" onclick="searchWithField()"><i class="fa fa-search"></i></button>
</form>
</div>
<script src="resources/javascript/script.js"></script>
</body>
<footer>
<span class="shapes">● ▴ ■</span>
</footer>
</html>