Need to implement the search Bar functionality and want to Render the Filtered Data on UI

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]);
      }
  }
}

New contributor

Ankit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật