


JavaScript multi-condition filtering: implement dynamic product filtering based on AND/OR logic
introduction
In modern web applications, dynamic filtering is a key component in improving user experience. When users need to filter products or data based on multiple attributes (such as color, size, brand, etc.), how to effectively implement multi-condition filtering and flexibly handle the logical relationships between different filtering conditions (such as "AND" or "OR") has become a common challenge in front-end development. This tutorial will dive into how to build a robust multi-condition filtering system using pure JavaScript, with particular attention to how to dynamically switch AND/OR logic based on the number of filters selected by the user.
Core concepts and data structures
To implement multi-condition filtering, you first need to ensure that the HTML element contains enough metadata for JavaScript to read. In this example, we use the data-* attribute to store the color and size information of the product. To simplify the processing, we merge the colors and dimensions in a data-colors property and separate them with spaces.
For example:
<div class="filterable" data-colors="blue large">Product A</div> <div class="filterable" data-colors="green small">Product B</div>
Here, the first value of data-colors represents the color and the second value represents the size. This method requires strict consistency in the data format.
To distinguish between different types of filters (such as color filters and size filters), we add specific class names to them: color-checkbox and size-checkbox, while preserving the common filter-checkbox class.
HTML structure
The following is the HTML structure required to implement multi-condition filtering. It includes a checkbox group of colors and sizes, as well as a list of products to be filtered.
<div> <h3>Color</h3> <label><input type="checkbox" class="filter-checkbox color-checkbox" value="red">Red</label> <label><input type="checkbox" class="filter-checkbox color-checkbox" value="green">Green</label> <label><input type="checkbox" class="filter-checkbox color-checkbox" value="blue">Blue</label> </div> <div> <h3>Size</h3> <label><input type="checkbox" class="filter-checkbox size-checkbox" value="small">small</label> <label><input type="checkbox" class="filter-checkbox size-checkbox" value="medium"></label> <label><input type="checkbox" class="filter-checkbox size-checkbox" value="large">Large</label> </div> <div> <h1>Filter results</h1> <div class="filterable" data-colors="blue large">Product A</div> <div class="filterable" data-colors="green small">Product B</div> <div class="filterable" data-colors="red medium">Product C</div> <div class="filterable" data-colors="red large">Product D</div> </div>
JavaScript implementation
JavaScript is the core of implementing dynamic filtering. We will build the filter logic through the following steps:
- Get DOM elements: Select all relevant check boxes and filterable product elements.
- Define updateFilter function: This is the main function that handles filtering logic, which is called every time the checkbox state changes.
- Extract selected values: Get all selected values from the Color and Size checkbox groups respectively.
- Handle No Filter Conditions: If no filter conditions are selected, all products are displayed.
- Traversal and apply filtering logic: traversal each product element and apply complex AND/OR logic to determine its display status based on the selected filtering criteria.
- Event Listening: Add a change event listener for all check boxes.
- Initial filtering: Execute updateFilter once when the page is loaded to reflect the default filtering status.
// Get all filter checkboxes const filterCheckboxes = document.querySelectorAll('.filter-checkbox'); // Get color filter checkbox const colorCheckboxes = document.querySelectorAll('.color-checkbox'); // Get size filter checkbox const sizeCheckboxes = document.querySelectorAll('.size-checkbox'); // Get all filterable product elements const filterables = document.querySelectorAll('.filterable'); /** * Update the function for filtering results. * Dynamically display or hide products based on the checkbox status selected by the user. */ function updateFilter() { // Get all selected color values const colorChecked = Array.from(colorCheckboxes) .filter(checkbox => checkbox.checked) .map(checkbox => checkbox.value); // Get all selected size values const sizeChecked = Array.from(sizeCheckboxes) .filter(checkbox => checkbox.checked) .map(checkbox => checkbox.value); // If no filter criteria are selected, all products are displayed and exit if (!(colorChecked.length > 0 || sizeChecked.length > 0)) { filterables.forEach(filterable => { filterable.style.display = 'block'; }); return; } // traverse each filterable product element filterables.forEach(filterable => { // parse the product's color and size from the data-colors attribute // Assume the format is "color value_size value" const itemAttributes = filterable.dataset.colors.split(' '); const itemColor = itemAttributes[0]; const itemSize = itemAttributes[1]; let shouldDisplay = false; // Mark whether the product should be displayed// Case 1: Both color and size filters have selected items (apply AND logic) if (colorChecked.length > 0 && sizeChecked.length > 0) { // The product must match the selected color and the selected size at the same time shouldDisplay = colorChecked.includes(itemColor) && sizeChecked.includes(itemSize); } // Case 2: Only the color filter has selected items (apply OR logic within colors) else if (colorChecked.length > 0) { // The product must match any selected color shouldDisplay = colorChecked.includes(itemColor); } // Case 3: Only the size filter has selected items (apply OR logic within sizes) else if (sizeChecked.length > 0) { // The product must match any selected size shouldDisplay = sizeChecked.includes(itemSize); } // Note: The situation where there is no filtering condition is processed at the beginning of the function// Set the product's display status according to the value of shouldDisplay filterable.style.display = shouldDisplay ? 'block' : 'none'; }); } // Add change event listener for all filterCheckboxes.forEach(checkbox => { checkbox.addEventListener('change', updateFilter); }); // Perform a filter when the page is loaded to reflect the default state updateFilter();
Notes and optimization suggestions
-
The robustness of data attributes: The current scheme depends on the fixed order of colors and dimensions in the data-colors attribute. If the data structure becomes more complex or the order may change, it is recommended to use independent data-color and data-size properties, for example:
<div class="filterable" data-color="blue" data-size="large">Product A</div>
This can make the parsing logic clearer and more scalable.
-
Multi-filter type extension: If you need to add more filter types (such as brand, material, etc.), the current if/else if structure will become verbose. More general approaches may be considered, such as:
- Stores the filter configuration in an array, each element containing the filter's class name and the corresponding data-* attribute name.
- Dynamically generate filter logic, loop through all filter types, check whether there are selected items, and combine conditions according to the rules.
-
Performance optimization: Frequently manipulating the style.display attribute of the DOM element directly can cause performance problems for pages that contain a large number of filterable products (hundreds or thousands). The following optimizations can be considered:
- Offline DOM operation: first remove elements that need to be hidden from the DOM, or add them to a DocumentFragment, and then update the DOM at once.
- CSS class switching: control the display/hiding of elements by adding/removing CSS classes, rather than directly modifying the style attribute. This allows CSS to take over animation and transition effects.
- Virtual list/pagination: If the data volume is very large, consider only rendering products visible to the current viewport, or implementing the paging function.
-
User experience enhancement:
- "Clear All Filters" button: Provides a button that allows the user to clear all selected filters in one click.
- Filter result count: Displays the number of products matched under the current filter conditions.
- Load indicator: When complex filtering operations are in progress, display a load indicator to avoid UI lag.
Summarize
This tutorial shows how to implement a flexible multi-condition dynamic filtering system using JavaScript that can intelligently switch between AND and OR logic based on the number of filters selected by the user. Through clear HTML structure, separate JavaScript logic and rational use of data attributes, we can build a user-friendly and powerful filtering interface. At the same time, it also emphasizes optimization strategies in performance, scalability and user experience that need to be considered in actual projects. Mastering these technologies will help you create more interactive and practical applications in web development.
The above is the detailed content of JavaScript multi-condition filtering: implement dynamic product filtering based on AND/OR logic. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



You can select elements with data attributes in JavaScript through the CSS attribute selector, and use the document.querySelector() or document.querySelectorAll() method to achieve this. 1. Use [data-attribute] to select an element with the specified data attribute (any value); 2. Use [data-attribute="value"] to select an element whose attribute value exactly matches; 3. Access the data attribute through element.dataset, where data-user-id corresponds to dataset.userId (replace

This article aims to solve the problem that the @pytest.mark.parametrize decorator cannot directly handle the data generated at runtime when using Pytest and Selenium for dynamic data-driven testing. We will explore the limitations of pytest.mark.parametrize in depth, and introduce in detail how to gracefully implement parameterized testing based on Selenium dynamic data acquisition through Pytest's pytest_generate_tests hook function to ensure the flexibility and efficiency of test cases.

This article details how to build an accurate timing counter using JavaScript. The counter is incremented once a minute, but only runs within preset working days (Monday to Friday) and working hours (such as 6am to 8pm). It can pause increments during non-working hours but display the current value and automatically reset on the first day of each month, ensuring the accuracy and flexibility of the counting logic.

This article aims to solve the problem of redirecting the external link redirect button in jQuery pop-up window causing jump errors. When a user clicks multiple external links in succession, the jump button in the pop-up may always point to the first clicked link. The core solution is to use the off('click') method to undo the old event handler before each binding of a new event, ensuring that the jump behavior always points to the latest target URL, thus achieving accurate and controllable link redirection.

This article will introduce how to use JavaScript to achieve the effect of clicking on images. The core idea is to use HTML5's data-* attribute to store the alternate image path, and listen to click events through JavaScript, dynamically switch the src attributes, thereby realizing image switching. This article will provide detailed code examples and explanations to help you understand and master this commonly used interactive effect.

This article explores how JavaScript scripts can be effectively accessed and manipulated when they are loaded and executed before the creation of DOM elements in web development. We will introduce three core strategies: directly passing element references through function return values, using custom events to achieve inter-module communication, and using MutationObserver to listen for DOM structure changes. These methods can help developers solve the challenges between JavaScript execution timing and dynamic content loading, ensuring that the script can correctly operate subsequently added elements, such as making them drag-able.

ES2023 has introduced a number of practical updates, marking the mature evolution of JavaScript. 1.Array.prototype.findLast() and findLastIndex() methods support search from the end of the array, improving the efficiency of processing logs or configurations; 2.Hashbang syntax (#!/usr/bin/envnode) enables JavaScript files to be executed directly in Unix-like systems; 3.Error.cause supports error chains, enhancing exception debugging capabilities; 4. The specifications of WeakMaps and Sets improve cross-engine consistency; in the future, decorators (Stage3), records and tuples (

Usedotnotationtoupdatepropertieswithknownnames;2.Usebracketnotationfordynamicorspecialcharacterpropertynames;3.UseObject.assign()toupdatemultiplepropertiesormergeobjects,notingitmutatestheoriginalunlessanemptyobjectisusedasthefirstargument;4.Usethesp
