Search Autocomplete is a common component for modern Web design. This can be done only by Alpine and TailwindCSS.
Version
Alpine 3.9
TailwindCSS 3.0
Search Autocomplete
The search result is filtered automatically by user’s input.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://unpkg.com/alpinejs" defer></script>
<script src="https://cdn.tailwindcss.com"></script>
<title>Alpine</title>
</head>
<body x-data="{ search: '', items: ['iPhone', 'iPod', 'iPad'] }">
<div>
<input x-model="search" class="w-52 border border-gray-200 px-2" />
</div>
<ul x-show="search" class="mt-2 w-52">
<template x-for="x in items.filter(x => x.startsWith(search))">
<li x-text="x" class="px-2" />
</template>
</ul>
</body>
</html>
Line 10
<body x-data="{ search: '', items: ['iPhone', 'iPod', 'iPad'] }">
search
: variable to hold user inputitems
: all data for search
Line 12
<input x-model="search" class="w-52 border border-gray-200 px-2" />
x-model
: two way binding for user input
Line 14
<ul x-show="search" class="mt-2 w-52">
x-show
:<ul>
is hidden whensearch
is empty
Line 15
<template x-for="x in items.filter(x => x.startsWith(search))">
<li x-text="x" class="px-2" />
</template>
x-for
: filter dynamically by user’s inputx-text
: display the filtered result
Conclusion
- For readability and maintainability, we can also use getter with
x-for