A live search is an enhanced search form that uses AJAX technology to deliver results or suggestions within the same view. This is different from a regular HTML input field that is given autocomplete powers from a modern browser like Chrome, Firefox or Safari. A live search is often an input field that has been programmed to load suggestions from a specific dataset.
July 6th, 2017: This article was rewritten to update the list of plugins, and include some bonus, non-jQuery libraries.
Using live search in your application greatly improves the user friendliness of your site. Whatever back-end technology you are using — PHP, Java, Python, Ruby — JavaScript is your best bet in implementing a client-side live search feature.
Before I proceed, I would like to point out that the term live search is a bit ambiguous. There’s no authoritative definition for that term. Other terms that are frequently used to mean the same thing are autocomplete and type ahead.
I’ve come across a number of solutions labeled as live search which lack certain critical features. For this article, I’ll only shortlist live search solutions that fit the definition I’ve defined above.
1. Ajax Live Search
The first one on this list is a pretty amazing open-sourced, live search jQuery plugin. It is well documented and works perfectly in Chrome, Firefox, Safari, Opera, and IE8. The most impressive feature is that it can return results in the form of a paginated table! How cool is that?
You can learn more about it in the following links:
2. Semantic UI Search Component
If you are into CSS frameworks, you should check out Semantic UI. They have a cool Search Component that allows you to implement live search on your forms very easily. Just take a look at this example code:
HTML:
<div class="ui search">
<input class="prompt" type="text" placeholder="Search GitHub...">
<div class="results"></div>
</div>
JavaScript:
$('.ui.search')
.search({
apiSettings: {
url: '//api.github.com/search/repositories?q={query}'
},
fields: {
results : 'items',
title : 'name',
url : 'html_url'
},
minCharacters : 3
})
;
It’s amazingly minimal yet powerful. If you use the API settings option, you can do customizations such as grouping results into categories!.
Semantic UI also comes in different flavors specifically built for React, Meteor, Ember, and Angular. Check out their integrations page for the full list.
To learn more, visit the following links.
3. jQueryUI Autocomplete
This is a jQuery widget that is part of the jQuery UI library. The library itself is a curated set of user interface components, effects, and themes built on top of jQuery.
Autocomplete comes with several templates to provide different implementations. Here is one such example:
HTML:
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds">
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
JavaScript:
$( function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#birds" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
});
} );
To learn more, visit the following links:
4. DevBridge jQuery AutoComplete
The DevBridge jQuery AutoComplete is a tiny JavaScript library that allows you to turn regular text input fields into autocomplete suggestion boxes. Its API is vast and well documented allowing you to perform quite a number of different configurations. Implementing it is quite simple, check out this example:
HTML:
<input type="text" name="country" id="autocomplete"/>
JavaScript(AJAX lookup):
// AJAX Lookup
$('#autocomplete').autocomplete({
serviceUrl: '/autocomplete/countries',
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
}
});
JavaScript(Local lookup):
var countries = [
{ value: 'Andorra', data: 'AD' },
// ...
{ value: 'Zimbabwe', data: 'ZZ' }
];
$('#autocomplete').autocomplete({
lookup: countries,
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
}
});
To learn more, visit the following link:
5. EasyAutocomplete
EasyAutocomplete is a highly customizable jQuery autocomplete plugin with all the commonly required features. It supports local and remote data sets in JSON, XML, and plain text formats. It also supports callback handlers along with some default styling.
What sets this plugin apart is their templates feature. Templates are used to define the results view. You can create a custom template or use one of the available built-in presets which include:
- Description Template
- Icon Right/Left Template
- Link Template
Implementing a basic autocomplete with this plugin is quite easy, see the following example code:
HTML:
<input id="countries"/>
JavaScript:
var options = {
url: "resources/countries.json",
getValue: "name",
list: {
match: {
enabled: true
}
},
theme: "square"
};
$("#countries").easyAutocomplete(options);
JSON:
[
{"name": "Afghanistan", "code": "AF"},
{"name": "Aland Islands", "code": "AX"},
{"name": "Albania", "code": "AL"},
{"name": "Algeria", "code": "DZ"},
{"name": "American Samoa", "code": "AS"}
]
To learn more, visit the following link:
6. PixaBay jQuery-autoComplete
Pixabay.com, a free stock site, have an awesome open-source autocomplete jQuery plugin you can use for your project. Originally they were using DevBridge’s jQuery Autocomplete (no 4. in the list). Later they created a fork and started updating it to meet their own needs. Eventually, they did so much hacking into the original source code they ended up with their own ultra lightweight optimized plugin.
The plugin is only 1.4 kB compressed with support for multiple data sources, callbacks and features a smart caching system. Here is an example implementation of the plugin:
JavaScript:
$('input[name="q"]').autoComplete({
source: function(term, response){
$.getJSON('/some/ajax/url/', { q: term }, function(data){ response(data); });
}
});
To learn more, visit the following links:
7. Marco Polo
This is a jQuery autocomplete plugin that was developed out of frustration for lack of reliable autocomplete plugins at the time. It features quality documentation, caching, memory selections, custom styling, callback handling, and WAI-ARIA support. It requires jQuery v1.4.3 or higher and supports all modern browsers (and even IE6!).
Implementing Marco Polo is quite simple. Here is a sample implementation:
HTML:
...
<head>
<script src="jquery.min.js"></script>
<script src="jquery.marcopolo.min.js"></script>
</head>
...
<body>
<input type="text" name="userSearch" id="userSearch">
</body>
JavaScript:
$('#userSearch').marcoPolo({
url: '/users/search',
formatItem: function (data, $item) {
return data.first_name + ' ' + data.last_name;
},
onSelect: function (data, $item) {
window.location = data.profile_url;
}
});
JSON(Source data):
[
{
"first_name": "James",
"last_name": "Butler",
"profile_url": "/users/78749",
},
{
"first_name": "Win",
"last_name": "Butler",
"profile_url": "/users/41480",
},
]
To learn more, visit the following links:
8. xDSoft Autocomplete Like Google
This is a lightweight autocomplete jQuery plugin with local and remote data source support. It features accent folding.
Here is an example code implementation:
JavaScript
$('#remote_input2').autocomplete({source:[
{
url:"/component/jquery_plugins/?task=demodata&q=%QUERY%",
type:'remote'
},
["One","Two","Three"]
]});
To learn more, visit the following links:
9. jQuery Typeahead Search
The jQuery Typeahead Search is an autocomplete plugin built with deep customization options. It works in all modern browsers from IE8+ and supports multiple internal and external AJAX callbacks.
If you check out the demo page, you will find numerous examples of different code implementations.
10. Algolia Autocomplete
This JavaScript library is capable of adding a fast and fully-featured autocomplete menu to a search box. It can be combined to work with Algolia’s Search Engine.
It supports all modern browsers from IE9 and is available as a jQuery plugin, an Angular directive and as a standalone library. Along with the usual features, it has security features such as protection against XSS attacks.
11. ng-bootstrap Typeahead
If you are using both Angular and Bootstrap in your project, you should be using the ng-bootstrap framework. It has a Typeahead component that works just like a regular jQuery autocomplete plugin.
It supports templates, local and remote datasets, and the usual livesearch features. Here’s a partial code implementation for a Wikipedia search:
HTML:
<div class="form-group" [class.has-danger]="searchFailed">
<label for="typeahead-http">Search for a wiki page:</label>
<input id="typeahead-http" type="text" class="form-control" [(ngModel)]="model" [ngbTypeahead]="search" placeholder="Wikipedia search" />
<span *ngIf="searching">searching...</span>
<div class="form-control-feedback" *ngIf="searchFailed">Sorry, suggestions could not be loaded.</div>
</div>
Typescript:
@Injectable()
export class WikipediaService {
constructor(private _jsonp: Jsonp) {}
search(term: string) {
if (term === '') {
return Observable.of([]);
}
let wikiUrl = 'https://en.wikipedia.org/w/api.php';
let params = new URLSearchParams();
params.set('search', term);
params.set('action', 'opensearch');
params.set('format', 'json');
params.set('callback', 'JSONP_CALLBACK');
return this._jsonp
.get(wikiUrl, {search: params})
.map(response => <string[]> response.json()[1]);
}
}
@Component({
selector: 'ngbd-typeahead-http',
templateUrl: './typeahead-http.html',
providers: [WikipediaService],
styles: [`.form-control { width: 300px; display: inline; }`]
})
export class NgbdTypeaheadHttp {
model: any;
searching = false;
searchFailed = false;
constructor(private _service: WikipediaService) {}
search = (text$: Observable<string>) =>
text$
.debounceTime(300)
.distinctUntilChanged()
.do(() => this.searching = true)
.switchMap(term =>
this._service.search(term)
.do(() => this.searchFailed = false)
.catch(() => {
this.searchFailed = true;
return Observable.of([]);
}))
.do(() => this.searching = false);
}
To learn more, visit the following links:
12. React Autosuggest
You can tell from the title this is not a jQuery plugin, but it’s JavaScript nevertheless. React Autosuggest is an open-source library with a vast number of configuration options. It’s mobile friendly, WAI-ARIA compliant, fully customizable and it integrates well with Redux and Flux.
It takes a bit of effort to set up, but once you do that, you get a live search plugin that behaves exactly the way you want it. Here is a partial code sample of the component:
return (
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
/>
);
Although the source documentation illustrates a solution using a local array for data source, you can easily swap that with a remote fetch call inside the onSuggestionsFetchRequested()
function.
To learn more, visit the following links:
13. W3Schools Ajax Live Search
If you are looking to avoid dependencies and implement a solution with pure JavaScript, then you should try out this solution provided by w3schools.com.
The back-end used in this example is using a PHP server. Obviously, you can substitute this with a server technology of your choice. The code requires data in XML format. You can refactor the code to accept JSON formats too.
The great thing about this solution is that it works with all modern browsers and older ones up to IE5!
HTML:
<form>
<input type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>
JavaScript:
function showResult(str) {
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
To learn more, visit the following link:
14. WordPress Live Search
If you are using WordPress, you will be pleased to know you can implement live search with minimal to no coding at all. All you need is to install and set up a WordPress plugin with live search functionality. The most popular one is Dave’s WordPress Live Search currently with over 10,000 active installs. It is compatible with most themes, comes with several configurable options and is easy to integrate with minimum fuss. It also comes with a YouTube tutorial that demonstrates the entire set up process.
To learn more, visit the following links:
Summary
I hope this list helps you choose a suitable live search solution for your project. Depending on your experience and project environment, some are easier to implement and customize than others.
There are still other countless capable solutions I haven’t listed. Perhaps you can help by listing them in the comments below.