morris menanya
morris menanya

Reputation: 63

How do i make a search using ransack gem without pressing the enter key or submitting the form

the code works well but i need it to initiate search and filter Model Items just by pressing the key and probably creating a 1 second delay before filter. this is my html.erb search snippet

<%= search_form_for @query, url: users_path, data: {search_delay_target: "form"}, method: :get, html: { class: "relative" } do |f| %>
  <div class="relative">
    <%= f.search_field :first_name_or_last_name_or_email_cont, placeholder: "Search...", data: { action: 'keydown->search-delay#search', search_delay_target: "input"},
         class: "block w-full rounded-md border-0 pl-10 py-2 pr-12 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6" %>
    <div class="absolute inset-y-0 left-0 flex py-3.5 pl-3">
      <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-5.5-5.5M10 14a7 7 0 1 1 0-14 7 7 0 0 1 0 14z"/>
       </svg>
     </div>
     <div class="absolute inset-y-0 right-0 flex py-1.5 pr-1.5">
       <kbd class="inline-flex items-center rounded border border-gray-200 px-1 font-sans text-xs text-gray-400">⌘K</kbd>
     </div>
  </div>
  <%= f.submit "Search", class: "hidden" %>
<% end %>

Upvotes: -1

Views: 46

Answers (1)

Nikhil bhatt
Nikhil bhatt

Reputation: 77

In order to achieve the functionality you need to write javascript.

searchField = document.getElementById('input-field')

searchField.addEventListener('input', function(event) => {
  const query = event.target.value.trim();
   // also use setTimeout if you want to have 1 second delay before search.
  setTimeout(() => {
    // search logic
  }, 1000)
  // write fetch logic here.
})

Upvotes: 0

Related Questions