Filter A Collection Of Items Based On Form Field Values – Filter Container

Category: Javascript | February 8, 2021
Views Total:725 views
Official Page:Go to website
Last Update:February 8, 2021


Filter A Collection Of Items Based On Form Field Values – Filter Container


Filter Container is a web component (custom element) used to filter a collection of items based on the value you selected or typed in a form field (like select, input, etc).

How to use it:

1. Import the Filter Container web component.

<script type="module" src="filter-container.js"></script>

2. Assign unique values to filterable elements.

  <li data-filter-content="asia">Afghanistan</li>
  <li data-filter-content="europe">Albania</li>
  <li data-filter-content="africa">Algeria</li>
  <li data-filter-content="south-america">Argentina</li>
  <li data-filter-content="australia">Australia</li>
  <li data-filter-content="asia">Bangladesh</li>
  <li data-filter-content="europe">Belgium</li>
  <li data-filter-content="europe">Belarus</li>

3. Create a select element containing options to filter those elements. The data-filter-delimiter is used to define the delimimter if your filterable elements have multiple values.

<select data-filter-bind="content" data-filter-delimiter=",">
  <option value="">All contents</option>
  <option value="africa">Africa</option>
  <option value="antarctica">Antarctica</option>
  <option value="australia">Australia</option>
  <option value="asia">Asia</option>

4. Create an empty element to display the filter results.

<span data-filter-results="country/countries" aria-live="polite"></span>

5. Wrap them into the filter-container custom element.

<filter-container data-oninit>

6. Hide items that don’t match the form field values.

.filter-content--hide {
  display: none;

You Might Be Interested In:

Leave a Reply