• Blogs (9)
    • 📱 236 - 992 - 3846

      đź“§ jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • 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.

    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.

      $(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.

    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" /> 
      </form>

    The codes work very well. By the way, the back-end is using PHP+MongoDB+MySQL.