Autocomplete

Implementing a text field with autocomplete.

Autocomplete is a feature that allows a user to quickly find an item by typing part of its name, or to get suggestions about what to type.

The best way to build autocomplete functionality with Sircl, is to combine a textfield with a datalist, and have the datalist updated by the server when text is entered.

In the following example, a textbox is used to ask for a company name. Through autocomplete, the textbox offers suggestions based on the Microsoft AdventureWorksLT database:

<form action="/CompanyInfo/Save" method="post">
  <label>Company:<br />
    <input type="text" name="company" autocomplete="off"
           list="companies"
           class="oninput-change"
           onchange-action="/CompanyInfo/Suggest"
           method="get"
           target="#companies"
           browser-cache="on" />
    <datalist id="companies"></datalist>
  </label>
  <p>
    <button type="submit"><i class="spinner"></i> Save</button>
  </p>
</form>

The INPUT element uses an onchange-action change-action attribute to retrieve suggestions. To have the change triggered not only when the field is left, but also when typing (on input), the textfield has an oninput-change class. When input is detected, this class waits for an idle time of 800ms and then issues a change event. A custom delay can be set by replacing the class with the oninput-changeafter attribute which takes the delay in seconds as value.

When typing "car", the following change action request is issued:

/CompanyInfo/Suggest?name=company&value=car&company=car

By default change-actions use the "get" method, but in this case the method would be inherited from the form. The method is set explicitely back to "get" using the method attribute. "Post" would work as well, but would not be cacheable by the browser.

The server responds to the request with a list of options. For instance:

<option value="Cash &amp; Carry Bikes" />
<option value="Go-cart and Bike Specialists" />

Because the target attribute specifies #companies as the target, the options are inserted in the datalist and appear as suggestions.

Browser caching is enabled to limit the number of requests to the server and speed up responses.

The textfield also has an autocomplete attribute set to "off". This may seem contradictory for an autocomplete texfield, but this is to disable the default autocomplete feature offered by the browser.

 

Working demo
Loading demo...

 

Requirements

This example requires following Sircl library files to be loaded:

or:

Or their non-minified counterparts.

See the Get Started section about how to set up your project to use the Sircl library.

 

Compatibility

Note that this autocomplete implementation does not work well with Microsoft Internet Explorer.