search
HomeWeb Front-endJS TutorialDetailed explanation of the use of jQuery plug-in autocomplete_jquery

This article mainly introduces in detail how to use the jQuery plug-in autocomplete, which has certain reference value. Interested friends can refer to

Autocomplete queries are sometimes used in projects. Just like the Google search box and Taobao product search function, if you enter a Chinese character or letter, the relevant entries starting with the Chinese character or letter will be displayed for the user to choose. The autocomplete plug-in completes this function.

autocomplete official website: http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/ (jQuery autocomplete plug-in can be downloaded).

Taobao product search function Effect:

Let’s use the autocomplete plug-in to achieve similar effects.

1. Create the AjaxPage.aspx page and define the WebMethod method in it to return all the prompt entries of the input box required for the search page. The background code is as follows:

using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Web.Services;
 
 public partial class AjaxPage : System.Web.UI.Page
 {
  [WebMethod]
  public static string GetAllHints()
  {
   Dictionary<string, string> data = new Dictionary<string, string>();
   data.Add("苹果4代iphone正品", "21782");
   data.Add("苹果4代 手机套", "238061");
   data.Add("苹果4", "838360");
   data.Add("苹果皮", "242721");
   data.Add("苹果笔记本", "63348");
   data.Add("苹果4s", "24030");
   data.Add("戴尔笔记本", "110105");
   data.Add("戴尔手机", "18870");
   data.Add("戴尔键盘", "30367");
 
   DataContractJsonSerializer serializer = new DataContractJsonSerializer(data.GetType());
 
   using (MemoryStream ms = new MemoryStream())
   {
    serializer.WriteObject(ms, data);
    return System.Text.Encoding.UTF8.GetString(ms.ToArray());
   }
  }
 }

Note: The data returned by this method The format is json string.

2. Create the search page Index.aspx, the front-end code is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
  <title></title>
 <link rel="Stylesheet" href="Styles/jquery.autocomplete.css" />
 <script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
 <script type="text/javascript" src="Scripts/jquery.autocomplete.js"></script>
 <script type="text/javascript">
  var v = 1;
  $(document).ready(function () {
   $.ajax({
    type: "POST",
    contentType: "application/json",
    url: "AjaxPage.aspx/GetAllHints",
    data: "{}",
    dataType: "json",
    success: function (msg) {
     var datas = eval(&#39;(&#39; + msg.d + &#39;)&#39;);
     $("#txtIput").autocomplete(datas, {
      formatItem: function (row, i, max) {
       return "<table width=&#39;400px&#39;><tr><td align=&#39;left&#39;>" + row.Key + "</td><td align=&#39;right&#39;><font style=&#39;color: #009933; font-family: 黑体; font-style: italic&#39;>约" + row.Value + "个宝贝</font>  </td></tr></table>";
      },
      formatMatch: function(row, i, max){
       return row.Key;
      }
     });
    }
   });
  });
 </script>
 </head>
 <body>
  <form id="form1" runat="server">
  <p>
  <center>
   <asp:TextBox ID="txtIput" runat="server" Width="400px"></asp:TextBox>
  </center>
  </p>
  </form>
 </body>
</html>

implementation The effect is as follows:

3. autocomplete parameter description

* minChars (Number)
The minimum number of characters that the user needs to input before triggering autoComplete.Default: 1, if set to 0, the list will be displayed when double-clicking in the input box or deleting the content in the input box

* width (Number)
Specifies the width of the drop-down box. Default: width of the input element

* max (Number)
The autoComplete drop-down displays the number of items.Default: 10

* delay (Number)
Activate autoComplete after a keystroke Delay time (in milliseconds).Default: Remote is 400 Local 10

* autoFill (Boolean)
Do you want it to be automatic when the user selects it? Fill the value of the user's current mouse position into the input box. Default: false

* mustMatch (Boolean)
If set to true, autoComplete will only allow matching results to appear in the input box, so when the user enters illegal characters, the drop-down box will not be available.Default: false

* matchContains ( Boolean)
Determine whether to check the match inside the string when comparing, such as whether ba matches ba in foo bar. This is more important when using cache. Do not mix with autofill.Default: false

* selectFirst (Boolean)
If set to true, the first value of the autoComplete drop-down list will be deleted when the user types the tab or return key. Automatically selected, even if it has not been manually selected (with keyboard or mouse). Of course, if the user selects an item, then the value selected by the user is used. Default: true

* cacheLength (Number)
The length of the cache. That is, how many records should be cached for the result set obtained from the database. Set to 1 to not cache. Default: 10

* matchSubset (Boolean)
Can autoComplete use caching of server queries? If the query results for foo are cached, then if the user enters foo, there is no need to After retrieval, use the cache directly. This option is usually turned on to reduce the load on the server and improve performance. It will only be effective when the cache length is greater than 1. Default: true

* matchCase (Boolean)
Compares whether the case sensitivity switch is turned on. It is more important when using cache. If you understand the previous option, this is not difficult to understand, just like whether foot should be FOO. Find it in the cache.Default: false

* multiple (Boolean)
Whether to allow multiple values ​​to be entered, that is, use autoComplete multiple times to input Multiple values. Default: false

* multipleSeparator (String)
If it is multiple selection, use Separate selected characters. Default: ","

* scroll (Boolean)
Whether to use scroll when the result set is larger than the default height DisplayDefault: true

* scrollHeight (Number)
    自动完成提示的卷轴高度用像素大小表示 Default: 180 

* formatItem (Function)
    为每个要显示的项目使用高级标签.即对结果中的每一行都会调用这个函数,返回值将用LI元素包含显示在下拉列表中. Autocompleter会提供三个参数(row, i, max): 返回的结果数组, 当前处理的行数(即第几个项目,是从1开始的自然数), 当前结果数组元素的个数即项目的个数. Default: none, 表示不指定自定义的处理函数,这样下拉列表中的每一行只包含一个值.

* formatResult (Function)
    和formatItem类似,但可以将将要输入到input文本框内的值进行格式化.同样有三个参数,和formatItem一样.Default: none,表示要么是只有数据,要么是使用formatItem提供的值.

* formatMatch (Function)
    对每一行数据使用此函数格式化需要查询的数据格式. 返回值是给内部搜索算法使用的. 参数值row

* extraParams (Object)
    为后台(一般是服务端的脚本)提供更多的参数.和通常的作法一样是使用一个键值对对象.如果传过去的值是{ bar:4 },将会被autocompleter解析成my_autocomplete_backend.php?q=foo&bar=4 (假设当前用户输入了foo). Default: {}

* result (handler)
    此事件会在用户选中某一项后触发,参数为:
    event: 事件对象. event.type为result.
    data: 选中的数据行.
    formatted:formatResult函数返回的值
    例如:   

 $("#singleBirdRemote").result(function(event, data, formatted) {
  //如选择后给其他控件赋值,触发别的事件等等
 });

以上就是本文的全部内容,希望对大家的学习有所帮助

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor