Posts Tagged ‘howto’

using jQuery for an autocomplete field

Wednesday, April 15th, 2009

I had trouble figuring this out, so here it is…

  • Download the “autocomplete” library from http://docs.jquery.com/Plugins/Autocomplete .  Unzip it and put the contents (js and css files) somewhere where your web server can serve them.
  • Create your HTML to look like this:
<input type="text" class="ac_input" id="teams" />
  <div class="ac_results" style="display: none; position: absolute; width: 150px; top: 23px; left: 93px;">
    <ul style="overflow: auto; max-height: 180px;">
       <li class="ac_even"></li>
       <li class="ac_odd"></li>
    </ul>
  </div>
  • In the header of your page, put this (your URLs may differ, test them directly).  The first line pulls in the styles for the formatting.  The second pulls in the JavaScript for the autocomplete.  The script that is there (and should probably be in its own file) links the autocomplete code to your input field.:
  <link rel="stylesheet" type="text/css" href="/site_media/jquery-autocomplete/jquery.autocomplete.css" media="screen"/>
  <script type="text/javascript" src="/site_media/jquery-autocomplete/jquery.autocomplete.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
      var url = "/hoops/team_names";
      $("#teams").autocomplete(url, { limit : 10 } );
    });
  </script>
  • Now you have to create the code that will answer to /hoops/team_names/?q=[whatever is typed into the box]&limit=10.  In my Django app server, it looks like this:
from django.http import HttpResponse
def team_names(request):
    try:
        limit = request.GET['limit']
    except:
        limit = 10

    name = request.GET['q'].title()
    teams = Team.objects.filter(name__startswith=name)[:limit]
    ret = "\n".join([team.name for team in teams])

    return HttpResponse(ret)

Note that the responses are sent as a series of strings separated by newlines. I tried and tried to send back JSON-formatted data, but I can’t make it work. Oh well, this is “good enough”.