使用Bootstrap的typeahead()和JSON填充输入

时间:2013-06-11 16:07:11

标签: jquery json bootstrap-typeahead

我正在尝试使用bootstrap的typeahead()函数来根据使用JSON的用户条目更新输入。我有JSON对象,将其格式化为key:value对,现在我需要以某种方式将其推送到typeahead函数。我试图评论代码,以便你知道我正在尝试做什么,因为我经历了它。无论如何,到目前为止我已经

jQuery ......

$("#search").on("input", function() {

  // Grab the data that we're going to use based on the user's input
  $.getJSON( "http://holidays.allinclusive.co.uk/external/destinations.ashx?query=" + $("#search").val() )

  // Once we've got it...
  .done(function(data) {

    // Create a new JSON object
    var myObject = { 'destinations': [] };

    // Loop through each of the 'suggestions' and for each one...
    $.each(data.suggestions, function (index, elem) {

      // Create a new object
      var currentObject = {}

      // Then we're going to use key value pairs {value: data.value, location: suggsestion.location}
      currentObject['value'] = [data.data[index]];
      currentObject['location'] = elem;

      // Push each object to myObject
      myObject.destinations.push(currentObject);

    });

    // Now with the myObject we're going to use it for .typeahead() on input#search
    $('#search').typeahead({ 

      // Grab the object we need
      source: myObject,

      // Now let's select the value from whatever the user wants
      updater: function(item) {
        selectedDestination = myObject.destinations[ data.data[index] ];
        return item;
      }
    });       

  }); //.done
}); //.on

最后是HTML ......

<div class="well">  
    <input type="text" id="search" data-provide="typeahead" data-items="5">
</div>

有人可以帮我把这个拼凑起来吗?我已经花了两天的时间在论坛和网络上观看,现在已经用尽了头发!

由于

1 个答案:

答案 0 :(得分:0)

根据docssource接受arrays / functions,而非objects。此外,source元素直接用作建议的值。

我要做的是使用myObject.destinations作为关联数组,将建议值作为键,然后将Object.keys(myObject.destinations)传递给source

在你的建议循环中:

...

// Push each object to myObject
myObject.destinations[currentObject['value']] = currentObject;

...

然后是你的typeahead声明:

...

// Grab the object we need
source: Object.keys(myObject.destinations),

// Now let's select the value from whatever the user wants
updater: function(item) {
  selectedDestination = myObject.destinations[ item ];
  return item;
}

...