How to filter your jquery autocomplete data while typing

前端 未结 4 1727
清酒与你
清酒与你 2020-12-16 07:19

So far I have the following

var aCleanData = [\'aaa\',\'aab\',\'faa\',\'fff\',\'ffb\',\'fgh\',\'mmm\',\'maa\'];

$(\'#my-input\').autocomplete({
    source:a         


        
4条回答
  •  独厮守ぢ
    2020-12-16 07:46

    One possible solution to get only results starting with the input value is to check the array elements before search by yourself:

    var aCleanData = ['aaa','aab','faa','fff','ffb','fgh','mmm','maa'];
    $('#my-input').autocomplete({
        source: aCleanData,
        minLength: 2,
        search: function(oEvent, oUi) {
            // get current input value
            var sValue = $(oEvent.target).val();
            // init new search array
            var aSearch = [];
            // for each element in the main array ...
            $(aCleanData).each(function(iIndex, sElement) {
                // ... if element starts with input value ...
                if (sElement.substr(0, sValue.length) == sValue) {
                    // ... add element
                    aSearch.push(sElement);
                }
            });
            // change search array
            $(this).autocomplete('option', 'source', aSearch);
        }
    });
    

    Also see my jsfiddle.

提交回复
热议问题