William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

jQuery+twitter’sbootstrap: autocomplete

jQuery: autocomplete

With the support of twitter bootstrap’s ‘Typeahead‘, the following is the front-side implementation of autocomplete.

  1. Make sure jquery.min.js is loaded.
    CDN or local depository all work.
  2. Make sure twitter bootstrap’s js and css are loaded.
    We use bootstrap’s Typeahead functionality.
  3. Make sure jquery’s doTimeout.js is loaded.
    The doTimeout.js is for better performance, control ajax request, reset form.
  4. 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.

    <script type="text/javascript">
    $(function() {
     var timer;
      source : function(typeahead, query) {
       if(query.length==0) return false;
       timer=setTimeout(function() {
           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;
          complete : function() {
           $('#waiting').css('visibility', 'hidden');
       }, 300);

    The timeout’s 300ms is an experienced value which can be adjusted.

  5. 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" /> 
  6. The codes work very well. By the way, the back-end is using PHP+MongoDB+MySQL.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: