點燈坊

失くすものさえない今が強くなるチャンスよ

Creating Search Autocomplete

Sam Xiao's Avatar 2022-01-14

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

auto000

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 input
  • items : 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 when search 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 input
  • x-text : display the filtered result

Conclusion

  • For readability and maintainability, we can also use getter with x-for