1

I'm trying to use bootstrap's typeahead() function to update an input based on a users entry using JSON. I've got the JSON object, formatted it into key:value pairs and now I need to somehow push it to the typeahead function. I've tried to comment on the code so that you're aware of what I'm trying to do as I go through it. Anyway, so far I have

The 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

And finally the HTML...

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

Can someone please help me piece this one together? I've spent 2 days looking on forums and the net and have now run out of hair to pull out!

Thanks

bencarter78
  • 3,555
  • 9
  • 35
  • 53
  • Probably you want this:- http://stackoverflow.com/questions/9232748/twitter-bootstrap-typeahead-ajax-example – pvnarula Jun 11 '13 at 16:10

1 Answers1

0

According to the docs, source accepts arrays/functions, not objects. In addition, source elements are used directly as the values for the suggestions.

What I would do is use myObject.destinations as an associative array with the suggestion values as keys, then pass Object.keys(myObject.destinations) to source.

In your suggestion loop:

...

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

...

And then your typeahead declaration:

...

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

...
faide
  • 11
  • 1