From jQuery-ui autocomplete to typeahead.js

I am porting my application to twitter-bootstrap and I would like to replace jquery-ui autocomplete with typeahead.js.

It would be better to use the function built into twitter-bootstrap, but I'm fine with an additional plugin for plugins if necessary.

My problem is that I have problems reproducing the current behavior, especially with the lack of results.

How would you do something like this?

$("#search").autocomplete({ source : myUrl, delay : 100, minLength : 2, select : function(event, ui) { // do whatever i want with the selected item }, response : function(event, ui) { if (ui.content.length === 0) { ui.content.push({ label : "No result", value : customValue }); } } }); 

Basically, if there is no result, I want to display a custom message in the component.

Thanks!

+7
source share
2 answers

In the latest version of Typeahead.js (0.10), you can now specify an empty template to display when no results are found.

  $('.typeahead').typeahead({ hint: true, highlight: true, minLength: 2 },{ name: 'examples', source: examples.ttAdapter(), templates: { empty: [ '<div class="empty-message">', 'unable to find any results that match the current query', '</div>' ].join('\n') } }); 
+3
source

Moving to bootstrap typeahead will look something like this.

 $('.typeahead').typeahead({ minLength:2, updater: function (item) { /* do whatever you want with the selected item */ }, source: function (typeahead, query) { /* put your ajax call here.. return $.get('/typeahead', { query: query }, function (data) { return typeahead.process(data); }); */ } }); 

EDIT:

I updated the demo to include a sorter and highlighter . I think this will give you the results you want.

  sorter: function(items) { if (items.length == 0) { var noResult = new Object(); items.push(noResult); } return items; }, highlighter: function(item) { if (dataSource.indexOf(item) == -1) { return "<span>No Match Found.</span>"; } else { return "<span>"+item+"</span>"; } }, 

Bootstrap Typeahead Demo

I don't think typeahead has a delay equivalent, but there are some workarounds for jquery for this.

+4
source

All Articles