Using autocomplete events

Hey, super basic question here. I’ve got autocomplete working, and now I’m trying to bind a function to the autocomplete:selected event. I cannot figure out the syntax and where in my js to put it (I’ve tried several different things, probably not worth listing out here).

Further details: I want to run my search function when a user clicks on a suggestion rendered by autocomplete (currently if you click on an autocomplete suggestion it fills the value into the input field, but nothing else happens of course). I tried binding the search event to the user clicking on the div of the suggestion (<div class="aa-suggestion" role="option" id="option-#"><span style="white-space: normal;">xxx</span>) but that runs the search function on the current value in the search field (i.e. “Ba”) rather than waiting for the value from the suggestion to get filled in (i.e. “Baking”). Of course I could keep hacking around this with setTimeout or something like that, but I assume there is a cleaner way to do this using the API events.

Ah, since I went from the tutorial to the github page I totally scrolled past the Usage section. Clearly this snippet shows me the answer:

autocomplete('#search-input', { hint: false }, [
    {
      source: autocomplete.sources.hits(index, { hitsPerPage: 5 }),
      displayKey: 'my_attribute',
      templates: {
        suggestion: function(suggestion) {
          return suggestion._highlightResult.my_attribute.value;
        }
      }
    }
  ]).on('autocomplete:selected', function(event, suggestion, dataset) {
    console.log(suggestion, dataset);
  });
1 Like

Hi Alex,

Looks like I am trying to do the same thing as you - getting it to submit on clicking the autocomplete suggestion.

I have added the extra bit at the end - .on('autocomplete:selected, ... ... ]);

Do I need any extra code after the console.log to actually tell it to submit?
(Submission works on my clicking of the search box still, but not when I click on the suggested term).
Do I need it to also have any JS from Instant Search?

It’s been a few months since I last fiddled with Algolia, so my memory is a bit rusty and not yet figured out what I am doing wrong.

Thanks :slight_smile:

autocomplete(
    '#queries_keyword_query',
      {
        hint: false
      },
      [ {
        source: autocomplete.sources.hits(index, {hitsPerPage: 5}),
        displayKey: 'name',
        templates: {
            suggestion: function(suggestion) {
                return suggestion._highlightResult.name.value;
             }
         }
      } ]).on('autocomplete:selected', function(event, suggestion, dataset) {
          console.log(suggestion, dataset);
          });

Hey Emily. I think you are almost there. What is the function you call to perform your search (aka “getting it to submit” as you called it)? All you need to do is call that function after (or instead of) the console.log you currently have.

For me it looks like this:

autocomplete : function() {
  	//initialize autocomplete on search input (trying to match raw search term with ID of item in database)
	$('#aa-search-input').autocomplete({ hint: false, debug: true }, [
	    {
	      source: $.fn.autocomplete.sources.hits(index, { hitsPerPage: 5 }),
	      displayKey: 'id',
	      templates: {
	        suggestion: function(suggestion) {
	          // get the id of the Algolia suggestion
	          return suggestion.id;
	        }
	      }
	    }
	  ]).on('autocomplete:selected', function(event, suggestion, dataset) {
	    //first I store the Algolia 'suggestion' in a javascript object called 'template data'
	    templateData.hasSubstitutes = true;
	    templateData.id = suggestion.id;
	    templateData.ingredient = suggestion.name;
	    // then I call my template function to display the results render results via handlebars template
	    view.renderResult();
	  });
  }

Hi Alex,

Thank you for the reply & help. :slight_smile:

I don’t have a code like that as yet, perhaps because my search up until this point has been bound to a click event on a form submit, and then sends the keyword through to the results page (GET) which uses Instant Search’s JS to display the results.

So I am looking to implement this to submit the form button (the form is the search box).

I can understand basic javascript when reading it, but not strong on writing it myself. (Something I do want to improve, however).

I notice at the end of your example you use renderResult. I am guessing that you are using yours to display without a page submission?

I suppose I would need my JS to say to submit (simulate click) the specific button element…?

Excellent, it works! :smiley:

Simply used:

document.getElementById("searchForm").submit();

1 Like

Hi Alex,Could you help me something?I am trying to add infinite scroll to autocomplete but i can not find anyway.

@bitsmanager.develope can you explain in more detail what you are trying to do, what you’ve currently tried, and what is going wrong?

I tried to search many indexes in one text box (product,blog,shop).Everything is ok with autocomplete.js at laravel scout .But if user find in text box ,there will be many data .if i set

hitsprerpage to 100

source: autocomplete.sources.hits(datasets[0].index, { hitsPerPage: 100}),my result box design is too long.That’s why i want to try to add infinite scroll to my js.

this is my js

var client = algoliasearch(“A2NG40IE0J”, “05ceb098ff5ba623b2fcc13e82bb4970”);
var enterPressed = true;

var datasets = [
{
displayKey: “products”,
index: client.initIndex(“products”),
type:“product”
},
{
displayKey: “blogs”,
index: client.initIndex(“blogs”),
type:“blog”

},
{
    displayKey: "shops",
    index: client.initIndex("shops"),
    type:"shop"

}

]

autocomplete("#aa-search-input", { hint: false }, [
{
maxShowItems: 5,
source: autocomplete.sources.hits(datasets[0].index, { hitsPerPage: 10}),
displayKey: datasets[0].displayKey,
templates: {

        header: '<div class="aa-suggestions-category">Products</div>',
        suggestion: function(suggestion) {
            // beware for XSS holes here
        return '<span> ' +
        suggestion._highlightResult.product_name.value 
        + '</span>' + suggestion.new_price +'MMK' ;
        },
        empty: function(result){

        return '<div class="error"> Sorry , No results for " '+result.query + ' " at Product section !</div>';
    },
  
    }
},
{
    source: autocomplete.sources.hits(datasets[1].index, { hitsPerPage: 10 }),
    displayKey: datasets[1].displayKey,
    templates: {

        header: '<div class="aa-suggestions-category">Blogs</div>',
        suggestion: function(suggestion) {
            // beware for XSS holes here
        return '<span>' +
        suggestion._highlightResult.title.value 
        + '</span>' ;
        },

        empty: function(result){

        return '<div class="error"> Sorry , No results for " '+result.query + ' " at Blog section !</div> ';
    }

    }
},
  {
    source: autocomplete.sources.hits(datasets[2].index, { hitsPerPage: 10}),
    displayKey: datasets[2].displayKey,
    templates: {
        
         header: '<div class="aa-suggestions-category">Shops</div>',
         dropdownMenu: '#my-custom-menu-template',
        suggestion: function(suggestion) {
            // beware for XSS holes here
        return '<span>' +
        suggestion._highlightResult.shop_name.value 
        + '</span>' ;
        },
        empty: function(result){

        return '<div class="error"> Sorry , No results for " '+result.query + ' " at Shop section ! </div>';
    }
    }
}

]).on(“autocomplete:selected”, function(event, suggestion, dataset) {
var type_value= document.getElementById(‘aa-search-input’).value;
// 1-indexed dataset
// var url = datasets[dataset-1].url;
var type = datasets[dataset-1].type;
console.log(type);
window.location.href = window.location.origin + ‘/advance_search?search_type=’ + type + ‘&query_string=’ + type_value;
enterPressed = true;
}).on(‘keyup’, function(event,dataset) {
if (event.keyCode == 13 && !enterPressed) {
var type_value= document.getElementById(‘aa-search-input’).value;
var type = datasets[dataset-1].type;
window.location.href = window.location.origin + ‘/advance_search?search_type=’ + type + ‘&query_string=’ + type_value;

        }

});