jQuery - DevBridge自动填充 - 更改建议格式

时间:2015-09-18 15:11:39

标签: jquery autocomplete

我从DevBridge获得了Autocomplete jQuery插件或多或少的工作方式。请看这里的小提琴: https://jsfiddle.net/shalan/bcex6oaq/。这是一个简单的郊区和城市查找,用户开始在他/她的郊区打字,自动完成显示相关的建议。当用户进行选择时,它将自动使用关联的城市和邮政编码填充下面的2个只读文本框。数据结构如下所示:

var suburbData = [
    {"value":"Eastcliffe", "data":{"city":"Westwood","code":"23145"}},    
    {"value":"Creastwich","data":{"city":"Westerlyn","code":"66365"}},    
    {"value":"South Woodbury Island","data":{"city":"Fairmoor","code":"89798"}},    
    {"value":"Faighcastle","data":{"city":"Westwood","code":"23144"}},
    {"value":"Brightkeep","data":{"city":"Merrowshore","code":"08872"}},    
    {"value":"Summerbank","data":{"city":"Wyvernfield","code":"10467"}},    
];

虽然效果很好,但我希望将建议列表格式化为:Suburb, City,但保留调用自动完成功能的文本框中的Suburb值。

示例:

  • 如果我开始输入ea,它应该告诉我:
    • " Eastcliffe,Westwood"
    • " Creastwich,Westerlyn"
  • 如果我选择" Eastcliffe,Westwood",那么我的onSelect功能应该运行,但文本框的值仍应保持为Eastcliffe

如何以这种方式格式化建议列表?

2 个答案:

答案 0 :(得分:9)

您可以使用formatResult功能:

  

formatResult:function(suggestion,currentValue){}自定义函数   格式化建议容器内的建议条目,可选。

代码:

$(function() {
    $('#suburb').autocomplete({
        lookup: theData,
        minChars: 1,
        formatResult: function(suggestion, currentValue){
            return suggestion.value+','+suggestion.data.city;
        }
    });
});

演示:https://jsfiddle.net/j6r9ka6y/

答案 1 :(得分:3)

您可以使用Autocomplete.formatResult

执行此操作

试试这个JS(检查完整代码的演示)

Autocomplete.formatResult = function (suggestion, currentValue) {
    var pattern = '(' + utils.escapeRegExChars(currentValue) + ')';

    return suggestion.value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/&lt;(\/?strong)&gt;/g, '<$1>') + " , " + suggestion.data.city;
};