【问题标题】:Populating input using Bootstrap's typeahead() and JSON使用 Bootstrap 的 typeahead() 和 JSON 填充输入
【发布时间】:2013-06-11 16:07:10
【问题描述】:

我正在尝试使用引导程序的 typeahead() 函数来更新基于用户使用 JSON 输入的输入。我得到了 JSON 对象,将其格式化为键:值对,现在我需要以某种方式将其推送到 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>

有人可以帮我把这个拼凑起来吗?我花了 2 天时间在论坛和网络上寻找,现在已经没有头发可以拔了!

谢谢

【问题讨论】:

标签: jquery json bootstrap-typeahead


【解决方案1】:

根据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;
}

...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-19
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多