Amara  Legros

Amara Legros

1595435657

Dropdown with search box in VueJs searchable dropdown

In this post we will learn how to create dropdown with search functionality in vuejs. To implement this feature we use vue js cdn and search box cdn. Below are the steps to implement search box in dropdown.

Step 1 : Add These CDN

<script src=https://unpkg.com/vuejs-datepicker></script> <script type=“text/javascript” src=“https://unpkg.com/vue-simple-search-dropdown@latest/dist/vue-simple-search-dropdown.min.js”>

Step 2 : Add Html Code

<html><body id=“app”><Dropdown class=“form-control” name=“subject” :options=“options” placeholder=“Please select an animal” autocomplete=“off”></Dropdown></body></html>

#javascript #vuejs

What is GEEK

Buddha Community

Dropdown with search box in VueJs searchable dropdown
Display Boxes

Display Boxes

1624963019

Custom Printed Soap Boxes | Wholesale Soap Packaging | Custom Packaging Pro

You have a great quality product in your hand, and now you are thinking of ways to represent it to the customers in a most appealing way. Many brands are afraid of spending money on custom boxes without knowing that it is the most cost-effecting way with various benefits. When designed with proper planning and creativity, custom packaging can result in money. You shouldn’t mind spending a little more to save money in the long run. You may disagree with us, but investment in customization and personalization can open new doors of success for your business.

How Custom Boxes for Soap Are a Cost-Effective Solution?

From our kitchen cabinets to the big supermarkets, custom boxes are everywhere. We are surrounded by customization, even if it is about selling a small cosmetic product. When you deal in the soap market, you have to face a lot of competition. You can’t compete in the market with a strategy of using plain cardboard boxes. Gone are the days when you can use a simple packaging solution. Today is the age of customization, and you have to use custom Boxes for Soap. These are not only affordable but also look good on the shelves and provide an ultimate customer experience. Let’s take a deeper look at how custom packaging is a cost-effective solution with several benefits.

Helps To Reduce Shipping Prices

During this pandemic, the e-commerce industry has grown too fast, and every brand is selling its products online. One thing which is keeping the manufacturer is the high shipping price. But to make the right decision, you need to understand how shipping prices work. It is not only about the weight of the box; consider dimensional weight as well. Even if you are shipping a small item like soap, the box size can increase the shipping cost. So, the firsts step towards price reduction is using the box which is according to the product size and also light in weight.

Maximum Durability Ensures Protection

It is one of the most faced issues which brands face. Damaged and broken products always result in returns which ultimately means additional cost. No brand will ever want to face negative reviews and customer backlash. You can avoid it by using durable and sturdy boxes. When it comes to protection, corrugate and cardboard soap boxers can outclass every other solution. These two materials are quite affordable and readily available in the market. Once again, it is highly recommended to use the right box size to avoid damage and returns. You can also use other packaging materials for added protection.

Increase Your Visibility with Pillow Boxes

When it comes to increasing your visibility and exposure in retail stores, there is no better option other than custom containers. These come in a variety of shapes and styles, which increase the customer’s interest in your product. Custom Pillow Boxes are the right choice to present your soap products on the shelves. You can customize the pillow packaging further with other customization options like window patching, lamination, and gold stamping. Unique solutions always make customers take a closer look at the product, and most probably they will end up buying it.

Right Box Size Help to Save Big

We have mentioned it before, but it needs more repetition. A wrong size box will always cost you more. If you are thinking that you can end up saving by choosing the standard size boxes for all the products, you are wrong. It will cost you more in form of damaged products and returns. Moreover, the bigger will be the size of the box, the more you have to pay for shipping. So, always choose the right size, which suits the product dimensions, and don’t leave too much space in the containers. A bigger size box will also make you use the protective material.

Cardboard And Paperboard Are the Cheapest Options

If you still think that custom boxes are way out of your range, we have still so many options for you. Take a simple corrugate or cardboard box in white or any plain color, print your logo on it, and you have a custom box in your hand. Getting a custom solution for your soap products has never been so easy. Today is the age of minimalism, and you can take advantage of this trend. Use simple customization for a natural and minimal look. Cardboard and corrugated are the most affordable option when it comes to custom material.

Happy Customers Result in Repeat Business and Positive Reviews

When it comes to benefits with custom packaging, there are several benefits that you can get. From product protection to the customer experience, you will get everything with a custom solution. The biggest benefits of providing a personalized experience are repeat business and positive reviews from the customers. When you put your heart and effort into the customization, customers will reward you with positive feedback. A good review from the customers will attract more customers to your business. Satisfied customers will bring business with repeat business and higher brand recall.

Kraft Boxes for Display Improve Sustainability

When it comes to being sustainable, there is no better option than Kraft. Use Kraft packaging boxes to display your products on the shelves. It will attract more and more eco-conscious customers, which will ultimately result in boosted sales. It is not only a cheap option but offers 100% recyclability. The presentation and display of your product have a greater role to play in drawing the attraction. Using the same old-style packaging will not going to help you out. Think of something innovative and try using Kraft boxes for better results. Find a solution that is not unique but meets the customer’s needs.

When it comes to soap packaging, Kraft Boxes for Display are a perfect choice. These are not only cost-efficient but result in customer satisfaction, repeat business, and reduced shipping cost. Find a solution that meets your needs without breaking the budget.

#boxes for soap #boxes for pillow #boxes for display #soap boxes #pillow boxes #display boxes

Hire Dedicated VueJS Developers

Want to Hire VueJS Developer to develop an amazing app?

Hire Dedicated VueJS Developers on the contract (time/project) basis providing regular reporting about your app. We, at HourlyDeveloper.io, implement the right strategic approach to offer a wide spectrum of vue.js development services to suit your requirements at most competitive prices.

Consult with us:- https://bit.ly/2C5M6cz

#hire dedicated vuejs developers #vuejs developer #vuejs development company #vuejs development services #vuejs development #vuejs developer

Erstellen Sie Such- und Produktfilter mit HTML, CSS und Javascript

Willkommen zum heutigen Tutorial. Im heutigen Tutorial erfahren Sie, wie Sie Filter erstellen und nach Produkten suchen. Um dieses Projekt zu erstellen, benötigen wir HTML, CSS und Javascript. Da dies ein ziemlich fortgeschrittenes Projekt ist, würde ich es keinem Javascript-Anfänger empfehlen. Wenn Sie ein Fortgeschrittener oder Experte in Javascript sind, können Sie auf jeden Fall weitermachen und dieses machen.

Lassen Sie uns einen Überblick darüber geben, was dieses Projekt wirklich ist. Das Projekt umfasst eine Reihe von Produktkarten. Jeder dieser Karten ist ein Name, ein Preis und eine Kategorie zugeordnet. Über diesen Tags befindet sich eine Suchleiste, in der Benutzer anhand des Namens nach einem Produkt suchen können.

Unterhalb der Suchleiste befindet sich eine Gruppe von Schaltflächen. Jede dieser Schaltflächen hat einen Kategorienamen. Wenn der Benutzer auf eine dieser Schaltflächen klickt, werden die Produkte angezeigt, die dieser bestimmten Kategorie entsprechen.

Projektordnerstruktur:

Lassen Sie uns nun zunächst die Projektverzeichnisstruktur erstellen, damit wir mit dem Codieren beginnen können. Wir beginnen damit, einen Projektordner mit dem Namen "Filters and Product Search" zu erstellen. In diesem Ordner erstellen wir drei Dateien. Das erste ist index.html, das zweite ist style.cssund das dritte ist script.js. Diese Dateien sind HTML-Dokumente, Stylesheets bzw. Skriptdateien.

HTML-Code:

Wir beginnen mit dem HTML-Code. Kopieren Sie zunächst den folgenden Code und fügen Sie ihn in Ihre HTML-Datei ein.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Product Filter And Search</title>
    <!-- Google Font -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="wrapper">
      <div id="search-container">
        <input
          type="search"
          id="search-input"
          placeholder="Search product name here.."
        />
        <button id="search">Search</button>
      </div>
      <div id="buttons">
        <button class="button-value" onclick="filterProduct('all')">All</button>
        <button class="button-value" onclick="filterProduct('Topwear')">
          Topwear
        </button>
        <button class="button-value" onclick="filterProduct('Bottomwear')">
          Bottomwear
        </button>
        <button class="button-value" onclick="filterProduct('Jacket')">
          Jacket
        </button>
        <button class="button-value" onclick="filterProduct('Watch')">
          Watch
        </button>
      </div>
      <div id="products"></div>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Um diesem Projekt Stile hinzuzufügen, verwenden wir CSS. Kopieren Sie nun den folgenden Code und fügen Sie ihn in Ihre CSS-Datei ein.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  border: none;
  outline: none;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #f5f8ff;
}
.wrapper {
  width: 95%;
  margin: 0 auto;
}
#search-container {
  margin: 1em 0;
}
#search-container input {
  background-color: transparent;
  width: 40%;
  border-bottom: 2px solid #110f29;
  padding: 1em 0.3em;
}
#search-container input:focus {
  border-bottom-color: #6759ff;
}
#search-container button {
  padding: 1em 2em;
  margin-left: 1em;
  background-color: #6759ff;
  color: #ffffff;
  border-radius: 5px;
  margin-top: 0.5em;
}
.button-value {
  border: 2px solid #6759ff;
  padding: 1em 2.2em;
  border-radius: 3em;
  background-color: transparent;
  color: #6759ff;
  cursor: pointer;
}
.active {
  background-color: #6759ff;
  color: #ffffff;
}
#products {
  display: grid;
  grid-template-columns: auto auto auto;
  grid-column-gap: 1.5em;
  padding: 2em 0;
}
.card {
  background-color: #ffffff;
  max-width: 18em;
  margin-top: 1em;
  padding: 1em;
  border-radius: 5px;
  box-shadow: 1em 2em 2.5em rgba(1, 2, 68, 0.08);
}
.image-container {
  text-align: center;
}
img {
  max-width: 100%;
  object-fit: contain;
  height: 15em;
}
.container {
  padding-top: 1em;
  color: #110f29;
}
.container h5 {
  font-weight: 500;
}
.hide {
  display: none;
}
@media screen and (max-width: 720px) {
  img {
    max-width: 100%;
    object-fit: contain;
    height: 10em;
  }
  .card {
    max-width: 10em;
    margin-top: 1em;
  }
  #products {
    grid-template-columns: auto auto;
    grid-column-gap: 1em;
  }
}

Javascript:

Schließlich müssen wir dem Filter Funktionen hinzufügen und auch die Suchfunktion implementieren. Damit es funktioniert, fügen wir Javascript hinzu. Kopieren Sie den unten angegebenen Code und fügen Sie ihn in Ihre Javascript-Datei ein.

let products = {
  data: [
    {
      productName: "Regular White T-Shirt",
      category: "Topwear",
      price: "30",
      image: "white-tshirt.jpg",
    },
    {
      productName: "Beige Short Skirt",
      category: "Bottomwear",
      price: "49",
      image: "short-skirt.jpg",
    },
    {
      productName: "Sporty SmartWatch",
      category: "Watch",
      price: "99",
      image: "sporty-smartwatch.jpg",
    },
    {
      productName: "Basic Knitted Top",
      category: "Topwear",
      price: "29",
      image: "knitted-top.jpg",
    },
    {
      productName: "Black Leather Jacket",
      category: "Jacket",
      price: "129",
      image: "black-leather-jacket.jpg",
    },
    {
      productName: "Stylish Pink Trousers",
      category: "Bottomwear",
      price: "89",
      image: "pink-trousers.jpg",
    },
    {
      productName: "Brown Men's Jacket",
      category: "Jacket",
      price: "189",
      image: "brown-jacket.jpg",
    },
    {
      productName: "Comfy Gray Pants",
      category: "Bottomwear",
      price: "49",
      image: "comfy-gray-pants.jpg",
    },
  ],
};

for (let i of products.data) {
  //Create Card
  let card = document.createElement("div");
  //Card should have category and should stay hidden initially
  card.classList.add("card", i.category, "hide");
  //image div
  let imgContainer = document.createElement("div");
  imgContainer.classList.add("image-container");
  //img tag
  let image = document.createElement("img");
  image.setAttribute("src", i.image);
  imgContainer.appendChild(image);
  card.appendChild(imgContainer);
  //container
  let container = document.createElement("div");
  container.classList.add("container");
  //product name
  let name = document.createElement("h5");
  name.classList.add("product-name");
  name.innerText = i.productName.toUpperCase();
  container.appendChild(name);
  //price
  let price = document.createElement("h6");
  price.innerText = "$" + i.price;
  container.appendChild(price);

  card.appendChild(container);
  document.getElementById("products").appendChild(card);
}

//parameter passed from button (Parameter same as category)
function filterProduct(value) {
  //Button class code
  let buttons = document.querySelectorAll(".button-value");
  buttons.forEach((button) => {
    //check if value equals innerText
    if (value.toUpperCase() == button.innerText.toUpperCase()) {
      button.classList.add("active");
    } else {
      button.classList.remove("active");
    }
  });

  //select all cards
  let elements = document.querySelectorAll(".card");
  //loop through all cards
  elements.forEach((element) => {
    //display all cards on 'all' button click
    if (value == "all") {
      element.classList.remove("hide");
    } else {
      //Check if element contains category class
      if (element.classList.contains(value)) {
        //display element based on category
        element.classList.remove("hide");
      } else {
        //hide other elements
        element.classList.add("hide");
      }
    }
  });
}

//Search button click
document.getElementById("search").addEventListener("click", () => {
  //initializations
  let searchInput = document.getElementById("search-input").value;
  let elements = document.querySelectorAll(".product-name");
  let cards = document.querySelectorAll(".card");

  //loop through all elements
  elements.forEach((element, index) => {
    //check if text includes the search value
    if (element.innerText.includes(searchInput.toUpperCase())) {
      //display matching card
      cards[index].classList.remove("hide");
    } else {
      //hide others
      cards[index].classList.add("hide");
    }
  });
});

//Initially display all products
window.onload = () => {
  filterProduct("all");
};

Ihre Produktsuche und -filterung ist nun fertig. Ich hoffe, Ihnen hat das Tutorial gefallen.

Crie filtros de pesquisa e de produto usando HTML, CSS e Javascript

Bem-vindo ao tutorial de hoje. No tutorial de hoje, aprenderemos como construir filtros e pesquisar produtos. Para criar este projeto, precisamos de HTML, CSS e Javascript. Como este é um projeto bastante avançado, eu não o recomendaria para um iniciante em javascript. Se você é um intermediário ou especialista em javascript, pode definitivamente ir em frente e fazer este.

Vamos ter uma visão geral do que esse projeto realmente é. O projeto inclui uma série de cartões de produtos. Cada um desses cartões tem um nome, preço e categoria atribuídos a eles. Acima dessas tags, há uma barra de pesquisa onde os usuários podem pesquisar um produto com base em seu nome.

Abaixo da barra de pesquisa, existe um grupo de botões. Cada um desses botões possui um nome de categoria. Quando o usuário clica em qualquer um desses botões, os produtos correspondentes a essa categoria específica serão exibidos.

Estrutura da pasta do projeto:

Agora vamos primeiro criar a estrutura do diretório do projeto para que possamos começar a codificar. Começamos criando uma pasta de projeto chamada - 'Filtros e Pesquisa de Produto'. Dentro desta pasta, criamos três arquivos. O primeiro é index.html, o segundo é style.csse o terceiro é script.js. Esses arquivos são documentos HTML, folhas de estilo e arquivos de script, respectivamente.

HTML:

Começamos com o código HTML. Primeiro, copie o código abaixo e cole em seu arquivo HTML.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Product Filter And Search</title>
    <!-- Google Font -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="wrapper">
      <div id="search-container">
        <input
          type="search"
          id="search-input"
          placeholder="Search product name here.."
        />
        <button id="search">Search</button>
      </div>
      <div id="buttons">
        <button class="button-value" onclick="filterProduct('all')">All</button>
        <button class="button-value" onclick="filterProduct('Topwear')">
          Topwear
        </button>
        <button class="button-value" onclick="filterProduct('Bottomwear')">
          Bottomwear
        </button>
        <button class="button-value" onclick="filterProduct('Jacket')">
          Jacket
        </button>
        <button class="button-value" onclick="filterProduct('Watch')">
          Watch
        </button>
      </div>
      <div id="products"></div>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Em seguida, para adicionar estilos a este projeto, usamos CSS. Agora copie o código abaixo e cole-o em seu arquivo CSS.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  border: none;
  outline: none;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #f5f8ff;
}
.wrapper {
  width: 95%;
  margin: 0 auto;
}
#search-container {
  margin: 1em 0;
}
#search-container input {
  background-color: transparent;
  width: 40%;
  border-bottom: 2px solid #110f29;
  padding: 1em 0.3em;
}
#search-container input:focus {
  border-bottom-color: #6759ff;
}
#search-container button {
  padding: 1em 2em;
  margin-left: 1em;
  background-color: #6759ff;
  color: #ffffff;
  border-radius: 5px;
  margin-top: 0.5em;
}
.button-value {
  border: 2px solid #6759ff;
  padding: 1em 2.2em;
  border-radius: 3em;
  background-color: transparent;
  color: #6759ff;
  cursor: pointer;
}
.active {
  background-color: #6759ff;
  color: #ffffff;
}
#products {
  display: grid;
  grid-template-columns: auto auto auto;
  grid-column-gap: 1.5em;
  padding: 2em 0;
}
.card {
  background-color: #ffffff;
  max-width: 18em;
  margin-top: 1em;
  padding: 1em;
  border-radius: 5px;
  box-shadow: 1em 2em 2.5em rgba(1, 2, 68, 0.08);
}
.image-container {
  text-align: center;
}
img {
  max-width: 100%;
  object-fit: contain;
  height: 15em;
}
.container {
  padding-top: 1em;
  color: #110f29;
}
.container h5 {
  font-weight: 500;
}
.hide {
  display: none;
}
@media screen and (max-width: 720px) {
  img {
    max-width: 100%;
    object-fit: contain;
    height: 10em;
  }
  .card {
    max-width: 10em;
    margin-top: 1em;
  }
  #products {
    grid-template-columns: auto auto;
    grid-column-gap: 1em;
  }
}

Javascript:

Finalmente, precisamos adicionar funcionalidade ao filtro e também implementar a função de pesquisa. Para fazer funcionar, adicionamos javascript. Copie o código abaixo e cole em seu arquivo javascript.

let products = {
  data: [
    {
      productName: "Regular White T-Shirt",
      category: "Topwear",
      price: "30",
      image: "white-tshirt.jpg",
    },
    {
      productName: "Beige Short Skirt",
      category: "Bottomwear",
      price: "49",
      image: "short-skirt.jpg",
    },
    {
      productName: "Sporty SmartWatch",
      category: "Watch",
      price: "99",
      image: "sporty-smartwatch.jpg",
    },
    {
      productName: "Basic Knitted Top",
      category: "Topwear",
      price: "29",
      image: "knitted-top.jpg",
    },
    {
      productName: "Black Leather Jacket",
      category: "Jacket",
      price: "129",
      image: "black-leather-jacket.jpg",
    },
    {
      productName: "Stylish Pink Trousers",
      category: "Bottomwear",
      price: "89",
      image: "pink-trousers.jpg",
    },
    {
      productName: "Brown Men's Jacket",
      category: "Jacket",
      price: "189",
      image: "brown-jacket.jpg",
    },
    {
      productName: "Comfy Gray Pants",
      category: "Bottomwear",
      price: "49",
      image: "comfy-gray-pants.jpg",
    },
  ],
};

for (let i of products.data) {
  //Create Card
  let card = document.createElement("div");
  //Card should have category and should stay hidden initially
  card.classList.add("card", i.category, "hide");
  //image div
  let imgContainer = document.createElement("div");
  imgContainer.classList.add("image-container");
  //img tag
  let image = document.createElement("img");
  image.setAttribute("src", i.image);
  imgContainer.appendChild(image);
  card.appendChild(imgContainer);
  //container
  let container = document.createElement("div");
  container.classList.add("container");
  //product name
  let name = document.createElement("h5");
  name.classList.add("product-name");
  name.innerText = i.productName.toUpperCase();
  container.appendChild(name);
  //price
  let price = document.createElement("h6");
  price.innerText = "$" + i.price;
  container.appendChild(price);

  card.appendChild(container);
  document.getElementById("products").appendChild(card);
}

//parameter passed from button (Parameter same as category)
function filterProduct(value) {
  //Button class code
  let buttons = document.querySelectorAll(".button-value");
  buttons.forEach((button) => {
    //check if value equals innerText
    if (value.toUpperCase() == button.innerText.toUpperCase()) {
      button.classList.add("active");
    } else {
      button.classList.remove("active");
    }
  });

  //select all cards
  let elements = document.querySelectorAll(".card");
  //loop through all cards
  elements.forEach((element) => {
    //display all cards on 'all' button click
    if (value == "all") {
      element.classList.remove("hide");
    } else {
      //Check if element contains category class
      if (element.classList.contains(value)) {
        //display element based on category
        element.classList.remove("hide");
      } else {
        //hide other elements
        element.classList.add("hide");
      }
    }
  });
}

//Search button click
document.getElementById("search").addEventListener("click", () => {
  //initializations
  let searchInput = document.getElementById("search-input").value;
  let elements = document.querySelectorAll(".product-name");
  let cards = document.querySelectorAll(".card");

  //loop through all elements
  elements.forEach((element, index) => {
    //check if text includes the search value
    if (element.innerText.includes(searchInput.toUpperCase())) {
      //display matching card
      cards[index].classList.remove("hide");
    } else {
      //hide others
      cards[index].classList.add("hide");
    }
  });
});

//Initially display all products
window.onload = () => {
  filterProduct("all");
};

Sua pesquisa e filtro de produto agora estão prontos. Espero que tenha gostado do tutorial.

CODE VN

CODE VN

1637911881

Tạo Bộ lọc Sản phẩm và Tìm kiếm Sử dụng HTML, CSS & Javascript

Chào mừng đến với hướng dẫn hôm nay. Trong hướng dẫn hôm nay, chúng ta sẽ học cách xây dựng bộ lọc và tìm kiếm sản phẩm. Để tạo dự án này, chúng ta cần HTML, CSS và Javascript. Vì đây là một dự án khá nâng cao, tôi sẽ không giới thiệu nó cho người mới bắt đầu sử dụng javascript. Nếu bạn là một trung cấp hoặc chuyên gia về javascript, bạn chắc chắn có thể tiếp tục và tạo ra cái này.

Hãy để chúng tôi có một cái nhìn tổng quan về dự án này thực sự là gì. Dự án bao gồm một loạt các thẻ sản phẩm. Mỗi thẻ này có tên, giá và danh mục được gán cho chúng. Phía trên các thẻ này, có một thanh tìm kiếm nơi người dùng có thể tìm kiếm một sản phẩm dựa trên tên của nó.

Bên dưới thanh tìm kiếm, có một nhóm các nút. Mỗi nút này có một tên danh mục trên đó. Khi người dùng nhấp vào bất kỳ nút nào trong số các nút này, các sản phẩm tương ứng với danh mục cụ thể đó sẽ được hiển thị.

Cấu trúc thư mục dự án:

Bây giờ trước tiên chúng ta hãy tạo cấu trúc thư mục dự án để chúng ta có thể bắt đầu viết mã. Chúng tôi bắt đầu bằng cách tạo một thư mục dự án có tên - 'Bộ lọc và Tìm kiếm Sản phẩm'. Bên trong thư mục này, chúng tôi tạo ba tệp. Đầu tiên là index.html, thứ hai là style.cssvà thứ ba là script.js. Các tệp này lần lượt là tài liệu HTML, biểu định kiểu và tệp tập lệnh.

HTML:

Chúng tôi bắt đầu với mã HTML. Trước tiên, hãy sao chép đoạn mã dưới đây và dán vào tệp HTML của bạn.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Product Filter And Search</title>
    <!-- Google Font -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="wrapper">
      <div id="search-container">
        <input
          type="search"
          id="search-input"
          placeholder="Search product name here.."
        />
        <button id="search">Search</button>
      </div>
      <div id="buttons">
        <button class="button-value" onclick="filterProduct('all')">All</button>
        <button class="button-value" onclick="filterProduct('Topwear')">
          Topwear
        </button>
        <button class="button-value" onclick="filterProduct('Bottomwear')">
          Bottomwear
        </button>
        <button class="button-value" onclick="filterProduct('Jacket')">
          Jacket
        </button>
        <button class="button-value" onclick="filterProduct('Watch')">
          Watch
        </button>
      </div>
      <div id="products"></div>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Tiếp theo để thêm kiểu cho dự án này, chúng tôi sử dụng CSS. Bây giờ sao chép mã bên dưới và dán nó vào tệp CSS của bạn.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  border: none;
  outline: none;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #f5f8ff;
}
.wrapper {
  width: 95%;
  margin: 0 auto;
}
#search-container {
  margin: 1em 0;
}
#search-container input {
  background-color: transparent;
  width: 40%;
  border-bottom: 2px solid #110f29;
  padding: 1em 0.3em;
}
#search-container input:focus {
  border-bottom-color: #6759ff;
}
#search-container button {
  padding: 1em 2em;
  margin-left: 1em;
  background-color: #6759ff;
  color: #ffffff;
  border-radius: 5px;
  margin-top: 0.5em;
}
.button-value {
  border: 2px solid #6759ff;
  padding: 1em 2.2em;
  border-radius: 3em;
  background-color: transparent;
  color: #6759ff;
  cursor: pointer;
}
.active {
  background-color: #6759ff;
  color: #ffffff;
}
#products {
  display: grid;
  grid-template-columns: auto auto auto;
  grid-column-gap: 1.5em;
  padding: 2em 0;
}
.card {
  background-color: #ffffff;
  max-width: 18em;
  margin-top: 1em;
  padding: 1em;
  border-radius: 5px;
  box-shadow: 1em 2em 2.5em rgba(1, 2, 68, 0.08);
}
.image-container {
  text-align: center;
}
img {
  max-width: 100%;
  object-fit: contain;
  height: 15em;
}
.container {
  padding-top: 1em;
  color: #110f29;
}
.container h5 {
  font-weight: 500;
}
.hide {
  display: none;
}
@media screen and (max-width: 720px) {
  img {
    max-width: 100%;
    object-fit: contain;
    height: 10em;
  }
  .card {
    max-width: 10em;
    margin-top: 1em;
  }
  #products {
    grid-template-columns: auto auto;
    grid-column-gap: 1em;
  }
}

Javascript:

Cuối cùng, chúng ta cần thêm chức năng vào bộ lọc và cũng thực hiện chức năng tìm kiếm. Để làm cho nó hoạt động, chúng tôi thêm javascript. Sao chép mã được cung cấp bên dưới và dán vào tệp javascript của bạn.

let products = {
  data: [
    {
      productName: "Regular White T-Shirt",
      category: "Topwear",
      price: "30",
      image: "white-tshirt.jpg",
    },
    {
      productName: "Beige Short Skirt",
      category: "Bottomwear",
      price: "49",
      image: "short-skirt.jpg",
    },
    {
      productName: "Sporty SmartWatch",
      category: "Watch",
      price: "99",
      image: "sporty-smartwatch.jpg",
    },
    {
      productName: "Basic Knitted Top",
      category: "Topwear",
      price: "29",
      image: "knitted-top.jpg",
    },
    {
      productName: "Black Leather Jacket",
      category: "Jacket",
      price: "129",
      image: "black-leather-jacket.jpg",
    },
    {
      productName: "Stylish Pink Trousers",
      category: "Bottomwear",
      price: "89",
      image: "pink-trousers.jpg",
    },
    {
      productName: "Brown Men's Jacket",
      category: "Jacket",
      price: "189",
      image: "brown-jacket.jpg",
    },
    {
      productName: "Comfy Gray Pants",
      category: "Bottomwear",
      price: "49",
      image: "comfy-gray-pants.jpg",
    },
  ],
};

for (let i of products.data) {
  //Create Card
  let card = document.createElement("div");
  //Card should have category and should stay hidden initially
  card.classList.add("card", i.category, "hide");
  //image div
  let imgContainer = document.createElement("div");
  imgContainer.classList.add("image-container");
  //img tag
  let image = document.createElement("img");
  image.setAttribute("src", i.image);
  imgContainer.appendChild(image);
  card.appendChild(imgContainer);
  //container
  let container = document.createElement("div");
  container.classList.add("container");
  //product name
  let name = document.createElement("h5");
  name.classList.add("product-name");
  name.innerText = i.productName.toUpperCase();
  container.appendChild(name);
  //price
  let price = document.createElement("h6");
  price.innerText = "$" + i.price;
  container.appendChild(price);

  card.appendChild(container);
  document.getElementById("products").appendChild(card);
}

//parameter passed from button (Parameter same as category)
function filterProduct(value) {
  //Button class code
  let buttons = document.querySelectorAll(".button-value");
  buttons.forEach((button) => {
    //check if value equals innerText
    if (value.toUpperCase() == button.innerText.toUpperCase()) {
      button.classList.add("active");
    } else {
      button.classList.remove("active");
    }
  });

  //select all cards
  let elements = document.querySelectorAll(".card");
  //loop through all cards
  elements.forEach((element) => {
    //display all cards on 'all' button click
    if (value == "all") {
      element.classList.remove("hide");
    } else {
      //Check if element contains category class
      if (element.classList.contains(value)) {
        //display element based on category
        element.classList.remove("hide");
      } else {
        //hide other elements
        element.classList.add("hide");
      }
    }
  });
}

//Search button click
document.getElementById("search").addEventListener("click", () => {
  //initializations
  let searchInput = document.getElementById("search-input").value;
  let elements = document.querySelectorAll(".product-name");
  let cards = document.querySelectorAll(".card");

  //loop through all elements
  elements.forEach((element, index) => {
    //check if text includes the search value
    if (element.innerText.includes(searchInput.toUpperCase())) {
      //display matching card
      cards[index].classList.remove("hide");
    } else {
      //hide others
      cards[index].classList.add("hide");
    }
  });
});

//Initially display all products
window.onload = () => {
  filterProduct("all");
};

Bộ lọc và tìm kiếm sản phẩm của bạn hiện đã sẵn sàng. Tôi hy vọng bạn thích hướng dẫn.