Tag Archives: jQuery autocomplete plug-in

Summary of jQuery autocomplete plug-in

Requirement: realize the prompt effect similar to Baidu search, that is, you can filter the options in the drop-down list through keywords

There are ready-made autocomplete plug-ins in layui and iView, but they need to integrate the dependencies related to layui and iView. I just want to realize this function in a simple business environment, and there is no integrated environment in the business framework of the system, so this method has low cost performance.

I found a case of using jQuery for integration on the Internet and studied it by myself. The notes in the original chestnut are not very clear, which is not easy for people like me who have not understood and studied the autocomplete component of jQuery before. Don’t talk too much nonsense. Paste the effect picture first

The above screenshot is an example, which I used for integration in my project. Ajax can achieve real-time access and fixed source array filter values. Next, I will post the codes of the two examples:

The first method is to use source array

    var countries = {
        "AD": "Andorra",
        "A2": "Andorra Test",
        "AE": "United Arab Emirates",
        "AF": "Afghanistan",
        "AG": "Antigua and Barbuda"
        }
    var countriesArray = $.map(countries, function (value, key) { return { value: value, data: key }; });
    $('#autocomplete-ajax').autocomplete({
        lookup: countriesArray,   // If this attribute is written, it means that a fixed array of data is used, even if the serviceUrl attribute is also available, it will not take effect
        lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
            var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
            return re.test(suggestion.value);
        },
        onSelect: function(suggestion) {
            $('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
        },
        onHint: function (hint) {
            $('#autocomplete-ajax-x').val(hint);
        },
        onInvalidateSelection: function() {
            $('#selction-ajax').html('You selected: none');
        }
    });

The second way: Ajax real-time access

    var countriesArray = $.map(countries, function (value, key) { return { value: value, data: key }; });

    //jQuery ajax mockļ¼ŒSimulate background processing of incoming requests
    $.mockjax({
        url: '*',
        responseTime: 2000,
        response: function (settings) {
            var query = settings.data.query,
                queryLowerCase = query.toLowerCase(),
                re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi'),
                suggestions = $.grep(countriesArray, function (country) {
                     // return country.value.toLowerCase().indexOf(queryLowerCase) === 0;
                    return re.test(country.value);
                }),
                response = { // Note that the return format must be in this format
                    query: query,
                    suggestions: suggestions
                };

            this.responseText = JSON.stringify(response);
        }
    });
    // Initialize ajax autocomplete:
    $('#autocomplete-ajax').autocomplete({
        serviceUrl: '/autosuggest/service/url',
        // lookup: countriesArray, // This must be commented out, otherwise the countriesArray array in the property will be used instead of taking the ajax request in the serviceUrl
        lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
            var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
            return re.test(suggestion.value);
        },
        onSelect: function(suggestion) {
            $('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
        },
        onHint: function (hint) {
            $('#autocomplete-ajax-x').val(hint);
        },
        onInvalidateSelection: function() {
            $('#selction-ajax').html('You selected: none');
        }
    });

In this way, we need to pay attention to the following points:

    1. when using serviceurl, the lookup attribute must be commented out; the serviceurl attribute is configured with the real request path of the background, and the above configuration is to simulate the background processing by using mockjax, and the corresponding mockjax code does not need to be reflected in the program; the format of the data returned by the background must be strictly in accordance with: {“query”: query, “suggestions”: suggestions}, Suggestions is the filtered data, and you can debug the specific format to understand it; </ OL>

The following is my own specific code:


$(function () {
    'use strict';

    // Initialize ajax autocomplete:
    $('#autocomplete-ajax').autocomplete({
        serviceUrl: 'http://127.0.0.1/test/autosuggest/userInfo/4028805e6d5e3155016d637627d80157',
        lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
            var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
            return re.test(suggestion.value);
        },
        onSelect: function(suggestion) {
            $('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
        },
        onHint: function (hint) {
            $('#autocomplete-ajax-x').val(hint);
        },
        onInvalidateSelection: function() {
            $('#selction-ajax').html('You selected: none');
        }
    });
    
});

last:

You are welcome to exchange and study with me. Because this article was written after the event, I can’t remember which God’s code was written at that time. The source code has to be written down. The website is as follows: www.jq22.com , the specific use of the case has not been found, the following is the source code link I downloaded before, can be downloaded for free, if there is infringement, please contact to delete.

be careful:

1. When using Ajax dynamic request, the plug-in will pass a query parameter to the background: I use @ requestparam (name = query “, required = false) string query to accept it;

2. When using Ajax dynamic request, the return format is fixed, and the name of the return attribute should not be modified. The return format code is as follows

@Getter
@Setter
@ToString
public class Result1 implements Serializable {

	@ApiModelProperty("Query criteria")
	private String query;
	
	@ApiModelProperty("return output")
	private List<Result12> suggestions;
}

@Getter
@Setter
@ToString
public class Result12 implements Serializable {

	@ApiModelProperty("name")
	private String value;
	
	@ApiModelProperty("key")
	private String data;
}