与国家/地区的JQuery自动完成功能

时间:2016-02-05 15:04:33

标签: javascript jquery jquery-ui autocomplete

我正在尝试使用jquery中的国家/地区代码进行自动填充。我以code为例。在我的网站中,它的效果非常好,但值显示为输入前面的列表,而不是网站中的示例。我无法在jsfiddle上运行它,但这里是my code。谢谢你!

var countries = {
    "Argentina (AR)":"AR",
    "United States (US)":"US",
    "Comoros": "KM",
    "Congo (Brazzaville)": "CG",
    "Congo, Democratic Republic of the": "CD",
    "Cook Islands":  "CK",
    "Costa Rica":  "CR",
    "Côte d'Ivoire": "CI",
    "Croatia": "HR",
    "Cuba":  "CU",
    "Cyprus":  "CY",
    "Czech Republic":  "CZ",
    "Denmark": "DK",
    "Djibouti":  "DJ",
    "Dominica":  "DM",
    "Dominican Republic":  "DO",
};

$( "#countryCodes" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB && $( this ).autocomplete( "instance" ).menu.active ) {
                event.preventDefault();
            }
        })
.autocomplete({
        minLength: 0,
        source: function( request, response ) {
            // delegate back to autocomplete, but extract the last term
            response( $.ui.autocomplete.filter(
            Object.keys(countries), extractLast( request.term ) ) );
        },
        focus: function() {
            // prevent value inserted on focus
            return false;
        },
        select: function( event, ui ) {
            var terms = split( this.value );
            // remove the current input
            terms.pop();
            // add the selected item
            terms.push( countries[ui.item.value] );
            // add placeholder to get the comma-and-space at the end
            terms.push( "" );
            this.value = terms.join( "," );
            return false;
        }
    });

2 个答案:

答案 0 :(得分:0)

一种解决方案是使用源数组提供自动完成功能。 jQuery的自动完成要求源数组包含属性为labelvalue的对象。您可以在定义countries对象后构建此数组,例如:

var mySource = Object.keys(countries).map(function(country) {
  return { 
    label: country, 
    value: countries[country] 
  };
});

...然后将其提供给自动填充:

$('#countryCodes').autocomplete({
  source: mySource
});

为了让你的小提琴运行,我必须注释掉你传递给自动完成小部件的其余内容,因为它有一些未定义的功能。

答案 1 :(得分:0)

小提琴中缺少exactLast函数。我现在添加,现在它在Fiddle中工作

function extractLast( term ) {
      return split( term ).pop();
    }

https://jsfiddle.net/px2dmd1o/1/

检查并告诉我您的问题