Add live suggestions and AI to search with jQuery


(Talk) #1

Got a large website with more assets than you know what to do with? It's quick and easy to improve discoverability by building in autosuggest and custom behaviours with nothing more than jQuery and a spare search asset tucked away somewhere.

 

1. Create a search asset in a hidden directory, customise as necessary.

 

2. Add an empty div beneath the search field in your website's design.

 

3. Add the following script to your behaviours .js file (create one if you don't have one), replace 'search_field' with the ID of your search input field, replace 'pathtosuggest' with the URL of your new search asset, ensure 'queries_suggest_query' reflects the name of your search query:

$('#search_field').keyup(function(){
var suggestion = $(this).val();
if(suggestion.length > 3){
$('#suggestions').load('pathtosuggest?queries_suggestion_query=' + suggestion);
}
});

Style it up with CSS, limit the number of results per page, and the results will impress.

 

Detailed instructions and tips for adding AI.


(Pomster09) #2

Hi Jeremy,

 

This is a great solution and works great.... Until... the space bar is pressed, then the suggestions disappear. Do you know of a way of addressing this? I'd love to use this method for two projects I have coming up, one is a knowledge bank, and the other is a dynamic questions and answered database. Both of these apps would be expecting the user to type more than one word.

 

Brilliant work!

 

Cheers

 

Wardy


(Talk) #3

Hi mate, I'm glad it's useful! I've only used it to match URLs so never thought about url encoding for phrases! Good find!

 

Wrap the var in a encodeURIComponent() and all should work well:

$('#search_field').keyup(function(){
var suggestion = $(this).val();
if(suggestion.length > 3){
$('#suggestions').load('pathtosuggest?queries_suggestion_query=' + encodeURIComponent(suggestion));
}
});

Let me know how you go.

 

Jeremy


(Pomster09) #4

Brilliant, that fixed it. I also had to add return false before it would work.

$('#queries_searchme_query').keyup(function() {
var suggestion = $(this).val();
if(suggestion.length > 2){
 $('#suggestions').load('http://www.mysearchpage.com/search?queries_suggestion_query='+ encodeURIComponent(suggestion));
 return false;
}
});

(Talk) #5

Awesome, is return false preventing browser suggestions based on previous searches?