The AutoSuggest pattern

Giving a text input the class "autosuggest" and a lang property of a URL, will query that URL on the server and return suggestions in a dropdown list.

The following files need including in the head of the document...


    <script src="../Include/Core.js" type="text/javascript"></script>
    <script src="../Include/jQuery.js" type="text/javascript"></script>
    <script src="../Include/ssAutoSuggest.js" type="text/javascript"></script>
    <link  href="../Include/ssAutoSuggest.css" type="text/css" rel="stylesheet"/>
          

Any inputs with class autosuggest will have this behaviour attached to them, with the autosuggest results being retrieved from the URL defined in the lang property.


    <form id="frmMain" action="PlayerDetails_AutoSuggest.asp" method="post">
      <p>
        <input type="text" class="autosuggest" lang="Players_AutoSuggest.asp" name="strPlayerDescription" id="strPlayerDescription" size="30" value="" />
        <input type="submit" name="submit" class="pushbutton" value="Go" />
      </p>
    </form>
          

On the server, the page should not HTML encode the results, and should separate them using line breaks.

The text in the input box is sent as the query string q.

An example of a server-side .asp page is shown below.


<!--#include File="../Include/DataSourceConnection.asp"-->
<!--#include File="../Include/CommonFunctions.asp"-->
<%
q = ReplaceApostrophes(Server.HTMLEncode(Request.QueryString("q")))
Set rsPlayers = Server.CreateObject("ADODB.Recordset")
strSQLPlayers = " SELECT PlayerID, PlayerDescription, PlayerNumber, PlayerCountry " & _
                " FROM Players " & _
                " WHERE PlayerDescription LIKE '%" & q & "%' " & _
                " ORDER BY PlayerNumber ASC"
rsPlayers.Open strSQLPlayers, cn, 3

Set objPlayerDescription = rsPlayers("PlayerDescription")
Set objPlayerNumber = rsPlayers("PlayerNumber")
Set objPlayerCountry = rsPlayers("PlayerCountry")

While NOT rsPlayers.EOF
  strPlayerDescription = objPlayerDescription
  intPlayerNumber = objPlayerNumber
  strPlayerCountry = objPlayerCountry
  %>
  <%=HTMLDecode(strPlayerDescription) & vbcrlf%>
  <%
  rsPlayers.MoveNext
WEnd
%>
          
  • Note that we HTMLDecode the value before passing it back (otherwise things like &amp; show through).
  • Note that the line ssAddLoadEvent(ssInitialiseAutoSuggest); is run automatically in ssAutoSuggest.js. This looks for hyperlinks of class "autosuggest" and attaches this behaviour to them.