jQuery+twitter'sbootstrap: autocomplete
Blogs20132013-01-10
jQuery: autocomplete
With the support of twitter bootstrap’s ’Typeahead’, the following is the front-side implementation of autocomplete.
- Make sure jquery.min.js is loaded.
CDN or local depository all work. - Make sure twitter bootstrap’s js and css are loaded.
We use bootstrap’s Typeahead functionality. - Make sure jquery’s doTimeout.js is loaded.
The doTimeout.js is for better performance, control ajax request, reset form. -
The following is my codes to do the ajax/json-style trigger.
javascript part:
Notice: the return is json-style keyword which is related to my previous blog.$(function() { var timer; $('#typeahead').typeahead({ source : function(typeahead, query) { if(query.length==0) return false; clearTimeout(timer); timer=setTimeout(function() { $.ajax({ url : form.attr('action'), type : form.attr('method'), data : 'q=' + query, dataType : 'JSON', async : false, cache : false, beforeSend : function() { $('#waiting').css('visibility', 'visible'); }, success : function(data) { // if json is null, means no match, won't do again. if(data==null || (data.length===0)) return; typeahead.process(data); }, complete : function() { $('#waiting').css('visibility', 'hidden'); } }); }, 300); } }); });The timeout’s 300ms is an experienced value which can be adjusted.
-
HTML Form part:
<form action="{{$__url__}}" method="get"> <input type="text" name="q" id="typeahead" data-provide="typeahead" autocomplete="off" placeholder="Keyword" /> <button type="submit" id="ns"> Search! </button> <img id="waiting" src="images/spinner.gif" width="16" height="16" border="0" />Â </form>
The codes work very well. By the way, the back-end is using PHP+MongoDB+MySQL.
