jQuery Typeahead - 未捕获的TypeError:无法读取未定义的属性“name”

时间:2015-06-29 14:53:37

标签: javascript jquery html twitter-bootstrap typeahead.js

我正在使用Bootstrap-3 Typeahead plugin以及Bootstrap Tag Input plugin。我这样用它:

<input type="text" id="name" name="test" data-provide="typeahead">

和jQuery:

$.get('/design/assets/advertisements/countries.json', function(data) {
    $("#name").typeahead({
        source: data
    });
    $('#name').tagsinput({
        typeahead: {
            source: data
        }
    });
}, 'json');

然而,typeahead和标签在某些方面起作用。每当我输入一些单词时,我都会得到建议,但每当我选择一个建议时,无论我写的是什么,都会在标签输入后添加。

示例:如果我写“Bah”并选择“Bahamas”,它看起来像这样:(我相信它会删除“Bah” )

enter image description here

我收到此错误 - 我不知道是不是这个原因:

Uncaught TypeError: Cannot read property 'name' of undefined

此文件调用错误:bootstrap3-typeahead.js

2 个答案:

答案 0 :(得分:5)

我已经下载了非最低版本的bootstrap-3 typeahead插件并更改了此内容:

displayText: function(item) {
  return item.name || item;
},

到这个

displayText: function(item) {
  if (typeof item == 'undefined') {
    return '';
  }
  return item.name || item;
},

它解决了这个问题。

实际上我不知道它是bootstrap-3 typeahead插件错误还是某些与我使用的bootstrap标签输入插件不兼容。

答案 1 :(得分:0)

我对Bootstrap 3进行了以下更改-在行号312中提前输入

旧代码:

displayText: function (item) {
      return typeof item !== 'undefined' && typeof item.name != 'undefined' && item.name || item;
},

更新代码:

displayText: function (item) {
        if(item){
                if(item.name){
                    return item.name;
                }
                return item;
        }
        else{
            return '';
        }
    },