jQuery Autocomplete Plugin Implementation
Implementing Autocomplete Functionality
To create an autocomplete feature using jQuery, follow these implementation steps:
Server-Side Implementation
public void GetAutocompleteData()
{
List<SearchItem> results = new List<SearchItem>();
results.Add(new SearchItem { Label = "iPhone 12 Pro", Id = "1001" });
results.Add(new SearchItem { Label = "iPhone Leather Case", Id = "1002" });
results.Add(new SearchItem { Label = "iPad Pro", Id = "1003" });
results.Add(new SearchItem { Label = "MacBook Air", Id = "1004" });
HttpContext.Current.Response.ContentType = "application/json";
HttpContext.Current.Response.Write(JsonConvert.SerializeObject(results));
HttpContext.Current.Response.End();
}
Client-Side Implementation
HTML:
<input type="text" id="searchInput" class="form-control" />
JavaScript:
$(function() {
$.ajax({
method: "POST",
url: "SearchPage.aspx?action=GetAutocompleteData",
data: {},
success: function(response) {
$("#searchInput").autocomplete(response, {
minChars: 1,
width: 300,
max: 20,
delay: 400,
matchContains: true,
formatItem: function(item, index, count) {
return item.Label + " [" + item.Id + "]";
},
formatResult: function(item) {
return item.Label;
}
}).result(function(event, item) {
console.log("Selected ID:", item.Id);
});
}
});
});
Required Dependencies:
<link href="~/Content/autocomplete.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.6.0.min.js"></script>
<script src="~/Scripts/autocomplete.js"></script>
Configuration Parameters
- minChars: Minimum characters to trigger autocomplete
- width: Dropdown width in pixels
- max: Maximum displayed suggestions
- delay: Input delay before triggering (ms)
- matchContains: Enable substring matching
- formatItem: Customizes suggestion display format
- formatResult: Formats final selection value
Browser Compatibility Note
For modern jQuery versions, replace deprecated browser detection:
const isFirefox = /firefox/.test(navigator.userAgent.toLowerCase());
const isWebKit = /webkit/.test(navigator.userAgent.toLowerCase());
const isOpera = /opera/.test(navigator.userAgent.toLowerCase());
const isIE = /msie/.test(navigator.userAgent.toLowerCase());