JQuery AutoComplete Auto-complement function

Source: Internet
Author: User
Tags javascript array

Using AutoComplete can be very simple to have the text box automatic complement full function hint.

In the HTML file to introduce AutoComplete JS files and CSS style files, as well as AutoComplete compressed in the jquery JS file, do not privately with a high version of jquery, may cause no effect.

The simplest example to copy from a netizen:

<! DOCTYPE html>  

The results are as follows:

The disadvantage is only to match the front, can not match the middle, I do not know if there is no relevant configuration changes, and then learn to look again.

Take a closer look at the AutoComplete (URL or data, [options]) method.

The AutoComplete method has two parameters, the first to fill in the URL address or data, the JQuery AutoComplete plug-in is to support AJAX-style call data, so you can fill in the address of the call, in addition, you can fill in the data directly, formatted as a JavaScript array, As our example, AutoComplete's other parameter [options] is an optional, we do not write in the example, but there are many configurable parameters in this argument, we still modify the above example.


$ (). Ready (function () {
    $ ("#website"). AutoComplete (websites, {
        minchars:0,
        max:5,
        autofill:true,
        mustmatch:true,
        matchcontains:true,
        scrollheight:220,
        formatitem:function (data, I, total) {
            Return "<I>" + data[0] + "</I>";
        }, Formatmatch:function (data, I, total) {return
            data[0];
        }, Formatresult:function (data) {return
            data[0];
        }    
    }
);

We've added several parameters to the options item.

Minchars represents the minimum characters that are filled in before the activation is automatically completed, where we set to 0, and when we double-click the text box and do not enter a character, the data is displayed and the effect is as follows:


Max represents the number of entries in the list, we set 5, so it shows 5, as shown above

AutoFill for automatic fill, is in the text box automatically filled with the conditions of the item, look at the figure, when we enter "G", the text box filled with "Google."

Mustmatch indicates that the entry must be matched, that is, what is entered in the text box must be the data in the parameter, and if it does not match, the text box is emptied

The Matchcontains representation contains a match, which is the data in the parameters, as long as the data contained in the text box is displayed, for example, in the above figure, we enter "G", and because "Sogou" contains a "G", it is displayed, If Matchcontains is set to Fasle, then "Sogou" does not display

ScrollHeight do not need to explain, look at the document will know.

The following 3 parameters Formatitem, Formatmatch, FormatResult are very useful, formatitem function is to format the list of items, such as we add "I", so that the list of words appear in italics, Formatmatch is used in conjunction with Formatitem, the role is, because the use of formatitem, so the contents of the entries have changed, and we want to match the original data, so use Formatmatch to make an adjustment to match the original data, FormatResult is the data that defines the final return, such as whether we want to return the original data, not the Formatitem data.

[Options] There are a lot of useful parameters, you can see its documentation.

Auto-complement of local JSON data:

<! DOCTYPE html>  

==================================================================

The server-side JSON data is invoked, and the service side is implemented with a servlet, and JSON data is generated using Fastjson. On the Maven warehouse download Fastjson This jar package, of course generate a JSON statement of many jars, can also be used in other.

Write a tool class that converts to JSON: \src\com\lifeix\util\fastjsonutil.java

This class is very simple, as follows:

Package com.lifeix.util;

Import Com.alibaba.fastjson.JSON;

/**
 * Created by Lhx on 14-12-10 pm 4:15
 *
 * @project jspproject * @package com.lifeix.util *
 @blog htt p://blog.csdn.net/u011439289
 * @email 888xin@sina.com
 * @Description/public
class Fastjsonutil {
    /**
     * Object entity is converted to JSON
     * @param object
     * @return
     /public
    static String Object2json ( Object) {
        json JSON = (JSON) Json.tojson (object);
        return json.tojsonstring ();
    }

Write a Servlet:src\com\lifeix\servlet\jsonservlet.java, mainly output JSON data to the foreground.

Package com.lifeix.servlet;

Import Com.lifeix.util.FastJsonUtil;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;

Import Java.util.Map; /** * Created by Lhx on 14-12-9 pm 4:19 * * @project jspproject * @package ${package_name} * @blog http://blog.csdn.ne t/u011439289 * @email 888xin@sina.com * @Description/public class Jsonservlet extends HttpServlet {protected VO ID doPost (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException {PRINTWR
        ITER PW = NULL; try {response.setcontenttype ("Application/json;
            Charset=utf-8 ");
            Response.setcharacterencoding ("UTF-8");
            Response.setheader ("Cache-control", "No-cache"); PW = Response. Getwriter ();
            list<map<string, string>> list = new arraylist<map<string, string>> ();

            map<string,string> map = new hashmap<string, string> ();
            Map.put ("name", "Link");
            Map.put ("num", "34");


            List.add (map);
            Map = new hashmap<string, string> ();
            Map.put ("name", "Li");

            Map.put ("num", "123");
            Map = new hashmap<string, string> ();
            Map.put ("name", "Tom");
            Map.put ("num", "76");

            List.add (map);
            Map = new hashmap<string, string> ();
            Map.put ("name", "Gnk");
            Map.put ("num", "583");

            List.add (map);

            String jsonstr = Fastjsonutil.object2json (list);
            Pw.print (JSONSTR);
        Pw.flush ();
        }catch (Exception e) {e.printstacktrace ();
     finally {if (PW!= null) pw.close ();   } protected void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IO
    Exception {this.dopost (request, response); }
}

Write the foreground JavaScript code as follows:

<! DOCTYPE html>  

This code is easy to understand, first use jquery Ajax technology in the page load from the background to get data, cache into names, then call the Autocompletefn function, the data to this function, and then call AutoComplete this plug-in, When the page is entered, it will have the function of automatic completion.

The final effect is:

========================================================

The individual AutoComplete project has been canceled and replaced by the AutoComplete of the jquery UI community, Address: http://jqueryui.com/autocomplete/

On this page, an example is also very simple, it can match the middle of the characters, special effects better. We can directly copy the code to run on their own machine, but because the reference JS and CSS files are to be downloaded on the network, so you have to ensure that your machine in the network situation can.

Code:

<!doctype html>  

Postscript:

When you call the JSON data locally, you want to console the returned data, Formatitem, Formatmatch, and FormatResult all three functions. The result is the following error, I have been looking for a long time do not know why.

Finally found that the middle of the formatmatch function is not to give the return statement:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.