How to Submit the autocomplete form to refine instantsearch?

Hi!

We use both instantsearch to populate the content of our blog category pages and autocomplete to replace the searchBox widget with an autocomplete UX, so that folks can have a snappy search experience.
It works nice, but, I noticed the autocomplete generated form generated by autocomplete() is not submittable. I would like it to behave like a regular form would, so that whatever string typed in the form refines the instantsearch results, so that they match the one previewed in the autocomplete.

Right now, the generated form input does not have the name attribute so i fix it by modifying the DOM:

document.querySelector('#search-searchbar .aa-Input').setAttribute('name', 'my_index_name[query]');

… and attaching a keydown event listener to the input

document.querySelector('#search-searchbar input').addEventListener('keydown', function(event) {
  if (event.keyCode === 13) {
    event.preventDefault();
    document.querySelector('#search-searchbar .aa-Form').submit();
  }
});

It leads to a page with a query var that correctly contains the search input value. Unfortunately, the instantsearch() does not use it to refine its results.

How can I tell the instantsearch instance to use the query var?

Here is the code, that i believe is relevant:

  const { autocomplete, getAlgoliaResults } = window['@algolia/autocomplete-js'];
  const { hits, pagination, menu, configure } = instantsearch.widgets;
  const { history } = instantsearch.routers;
  const { connectStats, connectMenu, connectHits, connectPagination, connectAutocomplete } = instantsearch.connectors;

  const instantSearchRouter = history();

  const searchClient= algoliasearch('XXXX', '123456789');
  const search = instantsearch({
    indexName: 'my_index_name',
    searchClient: searchClient,
    routing: true,
    // routing: {
    //   router: instantsearch.routers.history({ writeDelay: 400 }),
    //  },
     // set initial state to use query search
    initialState: {
      // This uses the `search` query parameter as the initial query
      query: new URL(window.location).searchParams.get('my_index_name[query]'),
  },

  });
1 Like

I found this article How to trigger instantsearch query by setting input value dynamically which pointed me in the right direction.



  let input = document.querySelector('#search-searchbar .aa-Input');
  // on Enter, submit the search form
  input.addEventListener('keydown', function(event) {
    if (event.keyCode === 13) {
      search.helper
      .setQuery(input.value)
      .search();
      event.preventDefault();
      return;
    }
  });
1 Like