2016-02-05 65 views
0

我想在jQuery中使国家代码自动完成。我以这个code为例。在我的网站中,它运行得非常好,但是这些值在输入前显示为一个列表,而不像站点中的示例。我无法在jsfiddle上运行它,但这里是my code。谢谢!JQuery自动完成与国家

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; 
     } 
    }); 

回答

0

一个解决方案是提供自动完成的源数组。 jQuery的自动完成需要源数组包含属性为labelvalue的对象。你可以定义你countries对象后,例如建立这个数组:

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

...然后提供给自动完成:

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

为了让您的提琴跑,我不得不注释掉休息您传递给自动填充小部件的原因是它有一些未定义的函数。

0

小提琴中缺少exactLast功能。我现在加入,在这里,现在它的工作原理在小提琴

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

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

检查,让我知道什么是你的问题

+0

谢谢你!我可以解决我的问题,我需要添加一些CSS来解决它。 – jorexe