jQuery realizes automatic completion of user input
- 2021-07-21 06:01:32
- OfStack
The Auto-complete plug-in in jQuery UI is used to realize the automatic input completion function. When people search for goods by using e-commerce platforms such as Taobao and JD.COM, they often only need to input one special character of the goods, and they can display a list menu similar to the character. Users can quickly choose by using the mouse or keyboard direction keys, thus realizing a good user experience.
1. The simplest user input is completed automatically
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="external nofollow" >
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
// Defines and initializes a collection of dictionary data sources
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
// Automatically complete plug-in functions
$( "#tags" ).autocomplete({
// Automatically complete dictionary library data source
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags"> Please enter : </label>
<input id="tags">
</div>
</body>
</html>
2 Automatic completion using remote data sources
Auto-complete plug-in can not only realize the automatic completion of local data sources, but also read remote data sources, such as reading data source information from the server.
By caching the server data into the browser, the retrieved data source is first stored in the cache variable.
$(function() {
// Custom cache variable
var cache = {};
// Automatically complete plug-in functions
$("#tags").autocomplete({
// Define the minimum number of characters entered by the user
minLenght: 2,
source: function(request, response){// Defining a remote access data source function
var term = request.term;// Define User Request Information Variables
if(term in cache) {// Determining whether the requested data exists in the cache
response(cache[term]);// True, reading data from the cache
return;
}
$.getJSON('data.json', request, function(data, Status, xhr) {
cache[term] = data.result;// Caching remote data
response(data.result);
});
}
});
});