Ask Your Question
3

Incorporating an option for "not found" in the search bar using Tailwind CSS and Alpine JS.

asked 2023-06-14 01:15:52 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-14 01:40:01 +0000

bukephalos gravatar image

To add an option for "not found" in the search bar using Tailwind CSS and Alpine JS, we can use the x-show directive to conditionally display a message when no results are found.

Here's an example:

<div class="relative">
  <input 
    class="py-2 px-4 w-full rounded-md border-gray-300 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 focus:outline-none"
    type="text"
    placeholder="Search"
    x-model="search"
  >
  <div 
    class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-600"
    x-show="!results.length"
  >
    <p class="text-sm">Not found</p>
  </div>
</div>

<div class="mt-4" x-show="results.length">
  <ul class="border border-gray-300 rounded-md divide-y divide-gray-200">
    <template x-for="result in results" :key="result.id">
      <li class="p-4 hover:bg-gray-50">
        <a :href="result.url">{{ result.title }}</a>
      </li>
    </template>
  </ul>
</div>

<script>
  const data = [
    { id: 1, title: "Result 1", url: "#" },
    { id: 2, title: "Result 2", url: "#" },
    { id: 3, title: "Result 3", url: "#" },
  ]

  const search = () => {
    return {
      search: "",
      results: [],
      searchQuery() {
        this.results = data.filter(item => item.title.toLowerCase().includes(this.search.toLowerCase()))
      }
    }
  }
</script>

In this example, we've added an x-show directive to the div containing the "Not found" message. This directive is set to !results.length, meaning that the message will only be displayed when there are no results.

We've also added an x-show directive to the div containing the search results. This directive is set to results.length, meaning that the results will only be displayed when there are results.

In the JavaScript section, we've defined a search function that creates a reactive object with a search property (bound to the search input using x-model) and a results property (which is initially an empty array).

We've also defined a searchQuery method that filters the data array based on the search term and updates the results property accordingly.

Overall, this example provides a simple way to provide feedback to users when there are no search results.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-14 01:15:52 +0000

Seen: 7 times

Last updated: Jun 14 '23