Hi I was working on this project and I was assigned some task where I have to fetch the data from an external Api and I have to implement a Search Bar where we can search on the basis of Title and Render it on the Ui. So I thought I should make an onclick event on the button and when it hits I will take the value from search Bar and filter it on the basis of title and I will render it on the UI but the functionality is not working. Help me to filter it out.
I want to implement a Search Bar Functionality and I have rendered the data on the UI and I want to implement the Search Functionality.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dropdown Sort Menu with Search, Pagination, and Favorite</title>
<link rel="stylesheet" href="script.css">
</head>
<body>
<header>
<nav>
<div class="left">
<div class="dropdown">
<button class="dropbtn">Sort</button>
<div class="dropdown-content">
<button id = "as" onclick="sortData('asc')">Ascending</button>
<button id = "ds" onclick="sortData('desc')">Descending</button>
</div>
</div>
</div>
<div class="center">
<form id="search-form">
<input type="text" id="search-box" placeholder="Search...">
<button type="submit" id="search-btn" onclick="fetchdata()">Search</button>
</form>
</div>
<div class="right">
<button id="fav-btn" onclick="toggleFavorite()">Favorite</button>
</div>
</nav>
</header>
<main>
<div class="posts" id="data-container">
</div>
</main>
<footer>
<div class="pagination" id="pagination">
<button onclick="changePage('prev')" id="prev-btn" disabled>Previous</button>
<span id="page-numbers">
<button onclick="renderPosts()">1</button>
<button onclick="goToPage(2)">2</button>
<button onclick="goToPage(3)">3</button>
<!-- Add more buttons for additional pages as needed -->
</span>
<button onclick="changePage('next')" id="next-btn">Next</button>
</div>
</footer>
<script src="script.js"></script>
</body>
</html>
JS
// // JavaScript code goes here
let originalDataa = [];
// // let currentPage = 1;
// // const itemsPerPage = 5;
// // function renderData(data) {
// // const container = document.getElementById('data-container');
// // container.innerHTML = ''; // Clear any existing content
// // const start = (currentPage - 1) * itemsPerPage;
// // const end = start + itemsPerPage;
// // const paginatedData = data.slice(start, end);
// // paginatedData.forEach(item => {
// // const itemElement = document.createElement('div');
// // itemElement.textContent = JSON.stringify(item, null, 2);
// // container.appendChild(itemElement);
// // });
// // }
// // async function fetchAndSortData(order,limit) {
// // const url = `https://dummyjson.com/products`;
// // const key = 'name'; // Change this to the key you want to sort by
// // try {
// // const response = await fetch(url);
// // const data = await response.json();
// // originalData = data; // Save original data
// // // const sortedData = data.sort((a, b) => {
// // // if (order === 'asc') {
// // // return a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0;
// // // } else {
// // // return a[key] > b[key] ? -1 : a[key] < b[key] ? 1 : 0;
// // // }
// // // });
// // renderData(data);
// // renderPagination(data);
// // } catch (error) {
// // console.error('Error fetching or sorting data:', error);
// // }
// // }
// // function renderData(data) {
// // const container = document.getElementById('data-container');
// // container.innerHTML = ''; // Clear any existing content
// // data.forEach(item => {
// // const itemElement = document.createElement('div');
// // itemElement.textContent = JSON.stringify(item, null, 2);
// // container.appendChild(itemElement);
// // });
// // }
// // function renderPagination(data) {
// // const pagination = document.getElementById('pagination');
// // const pageNumbers = document.getElementById('page-numbers');
// // pageNumbers.innerHTML
// // }
// const URI = "https://dummyjson.com/products"
// async function fetchdata() {
// const result = await fetch(URI);
// const data = await result.json();
// console.log(data);
// return data;
// }
// function renderpost(post){
// const section = document.querySelector('.posts');
// const postDiv = document.createElement('div')
// const postTitle = document.createElement('h2');
// const desc = document.createElement('title');
// const price = document.createElement('h4');
// postTitle.innerHTML = post.title;
// desc.innerHTML = post.description;
// price.innerHTML = post.price;
// postDiv.appendChild(postTitle)
// section.appendChild(section);
// }
// async function renderposts(){
// const posts = await fetchdata();
// console.log(posts)
// posts.forEach((post) =>renderpost(post))
// }
function sort_by_price_asc() {
return function (elem1, elem2) {
if (elem1.price < elem2.price) {
return -1;
} else if (elem1.price > elem2.price) {
return 1;
} else {
return 0;
}
};
}
function sort_by_price_dsc() {
return function (elem1, elem2) {
if (elem1.price > elem2.price) {
return -1;
} else if (elem1.price < elem2.price) {
return 1;
} else {
return 0;
}
};
}
const postsUrl = `https://dummyjson.com/products/`;
async function getPosts() {
let originalData = []
const res = await fetch(postsUrl);
const posts = await res.json();
originalData = posts
originalDataa = posts.products;
console.log(originalDataa)
return originalData;
}
function renderPost(post) {
const section = document.querySelector('.posts');
const postDiv = document.createElement('div');
const postTitle = document.createElement('h1');
const PostPrice = document.createElement('h3');
const PostBrand = document.createElement('h1');
const postDesc = document.createElement('div');
postDesc.innerText = post.description;
postDesc.style.color = "black"
postTitle.innerText = post.title;
PostPrice.innerText = post.price;
// console.log(postTitle);
postDiv.appendChild(postTitle);
postDiv.appendChild(postDesc);
postDiv.appendChild(PostPrice,"price")
section.appendChild(postDiv);
PostBrand.innerText = post.brand
section.appendChild(PostBrand)
const button = document.createElement('button');
button.innerHTML = "Favourite";
section.appendChild(button)
}
async function renderPosts(type) {
const posts = await getPosts();
const temp = posts.products;
if(type === "asc"){
temp.sort(sort_by_price_asc());
for(let x=0;x<temp.length;x++){
renderPost(temp[x]);
}
// console.log(temp);
}
else{
temp.sort(sort_by_price_dsc());
for(let x=0;x<temp.length;x++){
renderPost(temp[x])
}
// console.log(temp)
}
}
function sortData(type){
renderPosts(type)
}
function fetchdata(){
let x = document.getElementById("search-box")
console.log(x);
const answer = originalDataa;
for(let i=0;i<answer.length;i++){
if(answer[i].title === x){
renderPost(answer[i]);
}
}
}
Ankit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.