Discover how to build advanced search filtering and sorting with Lovable. Follow our step-by-step guide to create efficient, user-friendly web experiences.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Setting Up Your Lovable Project
index.html
that will serve as the main entry point of your app.searchSort.js
where all the search, filtering, and sorting logic will reside.
Adding Dependencies
index.html
file, include the Lovable built-in library for search filtering and sorting. Insert the following snippet inside the <head>
section:
<!-- Add Lovable search and sorting library from CDN -->
<script src="https://cdn.lovable.com/libs/lovable-sort-filter.min.js"></script>
Implementing Search Functionality
index.html
, add an input field where users can type in their search queries. Insert this code within the <body>
section before your main content:
<!-- Search Input Field -->
<input type="text" id="searchInput" placeholder="Search items..." />
searchSort.js
file, add an event listener for the input field that will capture the user input and filter the items accordingly. Insert the following code at the top of the file:
// Wait for the DOM to load
document.addEventListener('DOMContentLoaded', function() {
const searchInput = document.getElementById('searchInput');
const items = document.querySelectorAll('.item'); // items to be filtered
// Listen for keystrokes in the search input field
searchInput.addEventListener('input', function() {
const query = this.value.toLowerCase();
items.forEach(function(item) {
// Compare the item text content with the query
if(item.textContent.toLowerCase().includes(query)) {
item.style.display = '';
} else {
item.style.display = 'none';
}
});
});
});
Implementing Filtering Functionality
index.html
file. Place the following snippet below the search input:
<!-- Filter Dropdown Control -->
<select id="filterSelect">
<option value="all">All Categories</option>
<option value="category1">Category 1</option>
<option value="category2">Category 2</option>
</select>
searchSort.js
file, add code to listen for changes on the filter control. Assume that each item has a data attribute data-category
to indicate its category. Append this code right after the search functionality code:
document.addEventListener('DOMContentLoaded', function() {
// Existing search code here...
const filterSelect = document.getElementById('filterSelect');
// Listen for changes in filter dropdown
filterSelect.addEventListener('change', function() {
const selectedCategory = this.value;
items.forEach(function(item) {
const itemCategory = item.getAttribute('data-category');
if(selectedCategory === 'all' || itemCategory === selectedCategory) {
item.style.display = '';
} else {
item.style.display = 'none';
}
});
});
});
Implementing Sorting Functionality
index.html
. For example, create buttons that allow sorting by name or date. Place this code below the filtering dropdown:
<!-- Sorting Buttons -->
<button id="sortByName">Sort by Name</button>
<button id="sortByDate">Sort by Date</button>
searchSort.js
file, write functions to sort the list of items. Append the following code to implement sorting functionality:
document.addEventListener('DOMContentLoaded', function() {
// Existing search and filter code here...
const sortByNameBtn = document.getElementById('sortByName');
const sortByDateBtn = document.getElementById('sortByDate');
const container = document.getElementById('itemsContainer'); // container element holding all items
// Function to sort items by name
function sortByName() {
// Convert NodeList into array for sorting
const itemsArray = Array.from(items);
itemsArray.sort(function(a, b) {
return a.textContent.localeCompare(b.textContent);
});
// Append sorted items
itemsArray.forEach(function(item) {
container.appendChild(item);
});
}
// Function to sort items by date (assumes each item has a data-date attribute)
function sortByDate() {
const itemsArray = Array.from(items);
itemsArray.sort(function(a, b) {
return new Date(a.getAttribute('data-date')) - new Date(b.getAttribute('data-date'));
});
itemsArray.forEach(function(item) {
container.appendChild(item);
});
}
sortByNameBtn.addEventListener('click', sortByName);
sortByDateBtn.addEventListener('click', sortByDate);
});
itemsContainer
and include the proper data attributes (data-category
and data-date
):
<div id="itemsContainer">
<div class="item" data-category="category1" data-date="2023-09-01">Item A</div>
<div class="item" data-category="category2" data-date="2023-08-15">Item B</div>
<div class="item" data-category="category1" data-date="2023-07-20">Item C</div>
</div>
Integrating Everything in Lovable
index.html
file, include your searchSort.js
script at the end of the <body>
section by adding the following code snippet:
<!-- Include JavaScript for search, filtering, and sorting -->
<script src="searchSort.js"></script>
index.html
and searchSort.js
) are saved and that your Lovable project references each correctly.
Testing and Fine-Tuning the Application
const express = require('express');
const { MongoClient } = require('mongodb');
const app = express();
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
async function connectDB() {
await client.connect();
return client.db('lovableDB');
}
app.get('/api/lovables', async (req, res) => {
const { search, category, sortBy, order } = req.query;
const db = await connectDB();
let query = {};
if (search) {
query.$or = [
{ title: { $regex: search, $options: 'i' } },
{ content: { $regex: search, $options: 'i' } }
];
}
if (category) {
query.category = category;
}
let sortOptions = {};
if (sortBy) {
sortOptions[sortBy] = (order && order.toLowerCase() === 'desc') ? -1 : 1;
}
try {
const items = await db.collection('lovables')
.find(query)
.sort(sortOptions)
.toArray();
res.json({ success: true, data: items });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const express = require('express');
const axios = require('axios');
const app = express();
app.get('/api/lovables/external', async (req, res) => {
const { search, category, sortBy, order } = req.query;
try {
// Fetch data from an external API that provides base "lovable" items
const response = await axios.get('https://api.external-service.com/lovables', {
params: { category }
});
let items = response.data.items;
// Search filtering using case-insensitive matching on title and description
if (search) {
const searchLower = search.toLowerCase();
items = items.filter(item => {
return (item.title && item.title.toLowerCase().includes(searchLower)) ||
(item.description && item.description.toLowerCase().includes(searchLower));
});
}
// Sorting logic based on sortBy and order parameters
if (sortBy) {
items.sort((a, b) => {
if (a[sortBy] < b[sortBy]) return order === 'desc' ? 1 : -1;
if (a[sortBy] > b[sortBy]) return order === 'desc' ? -1 : 1;
return 0;
});
}
res.json({ success: true, data: items });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
app.listen(4000, () => {
console.log('Server running on port 4000');
});
const express = require('express');
const { Sequelize, DataTypes, Op } = require('sequelize');
const app = express();
const sequelize = new Sequelize('postgres://user:password@localhost:5432/lovableDB');
const Lovable = sequelize.define('Lovable', {
title: { type: DataTypes.STRING },
description: { type: DataTypes.TEXT },
category: { type: DataTypes.STRING },
rating: { type: DataTypes.FLOAT }
}, {
tableName: 'lovables',
timestamps: false
});
app.get('/api/lovables/search', async (req, res) => {
const { search, category, sortBy = 'rating', order = 'asc', minRating } = req.query;
const where = {};
if (search) {
where[Op.or] = [
{ title: { [Op.iLike]: `%${search}%` } },
{ description: { [Op.iLike]: `%${search}%` } }
];
}
if (category) {
where.category = category;
}
if (minRating) {
where.rating = { [Op.gte]: parseFloat(minRating) };
}
try {
const results = await Lovable.findAll({
where,
order: [[sortBy, order.toUpperCase()]]
});
res.json({ success: true, data: results });
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
sequelize.authenticate().then(() => {
app.listen(5000, () => {
console.log('Server running on port 5000');
});
}).catch(err => {
console.error('Database connection error:', err);
});
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Introduction
This guide explains best practices for building search filtering and sorting functionalities using AI code generators. The goal is to assist non-technical people in understanding how to leverage these tools to generate clean, efficient code that meets your application’s needs.
Prerequisites
Planning Your Search, Filtering, and Sorting Features
Setting Up Your Project Environment
Integrating AI Code Generators
Implementing Search Filtering Functionality
def search\_items(query, data):
# Convert the query to lowercase for case-insensitive search
query = query.lower()
# Return items where the query is found in item text
return [item for item in data if query in item.lower()]
Implementing Filtering and Sorting
def sort\_items(items, key='name', reverse=False):
# Sort items by the specified key
return sorted(items, key=lambda x: x[key], reverse=reverse)
Testing and Debugging
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.