Autocomplete
enhances an input to support server-driven searchA powerful, server-driven autocomplete component that enhances text input fields with intelligent suggestions. Built on the browser’s native datalist functionality, this component provides fast, accessible autocomplete features without requiring heavy JavaScript frameworks.
Key Features
- Server-Driven: Fetches suggestions from your backend API in real-time
- Native Performance: Uses browser’s built-in
datalistfor optimal performance - Accessible: Full keyboard navigation and screen reader support
- Flexible Data: Works with any JSON API endpoint
- Custom Formatting: Transform server data for display and submission
- Progressive Enhancement: Works as regular text input without JavaScript
- Lightweight: Minimal JavaScript footprint
- Search Integration: Automatically integrates with Project Forge’s search system
How It Works
The autocomplete component follows a simple request-response cycle:
- User Types: As the user types in the input field, the component captures keystrokes
- API Request: After a brief delay, it sends a request to your specified endpoint
- Server Response: Your server returns a JSON array of matching objects
- Display Suggestions: The component formats the data and shows suggestions using a
datalist - User Selection: User can select a suggestion or continue typing custom text
Basic Usage
Step 1: Create the HTML Input
Start with a standard HTML input element:
<input id="user-search" name="user_id" placeholder="Search for a user..." />
Step 2: Initialize the Autocomplete
Add JavaScript to transform the input into an autocomplete field:
1 | |
API Reference
TypeScript Function Signature
function autocomplete(el: HTMLInputElement, url: string, field: string, title: (x: unknown) => string, val: (x: unknown) => string) {
Parameters:
- el (HTMLInputElement): The input element to enhance
- url (string): API endpoint URL for fetching suggestions
- field (string): Query parameter name for the search term
- title (function): Function to format display text from API objects
- val (function): Function to extract submission value from API objects
Server Response Format
Your API endpoint must return a JSON array of objects. The structure of each object is flexible, but should contain the data needed by your title and value functions:
Simple User Search
1 | |
Location Search
1 | |
Form Integration
Autocomplete works seamlessly with Project Forge form helpers:
1 | |