SB2055
SB2055

Reputation: 12852

Why is twitter bootstrap's typeahead not working here?

I'm trying to get typeahead.js working in my project. I have bootstrap loaded in my project (downloaded the source from the bootstrap site just now). Looking in the source shows no mention of typeahead, so I included the standalone js file.

I'm not getting any errors when I try to use it, but it's just not working. Simple code:

<input type="text" class="typeahead" />

var source = ["test1", "test2", "test3", "test4"];

$('.typeahead').typeahead({
    source: source })

jsfiddle: link

What am I doing wrong? (note my js is at the bottom of the jsfiddle)

Upvotes: 0

Views: 84

Answers (1)

OozeMeister
OozeMeister

Reputation: 4859

You're using a different version of typeahead.js than how you're calling it.

The latest version of typeahead expects a variable number of dataset arguments. See my updated version of your fiddle: http://jsfiddle.net/DTcHh/458/

var source = ["test1", "test2", "test3", "test4"];

function mySource(query, callback){
  srcs = [];
  for(var idx in source){
      var src = source[idx];
      if(src.indexOf(query) !== -1){
        srcs.push({value: src});
      }
  }
  console.log(srcs);
  callback(srcs);
}

$(document).ready(function(){
    var t = $(".typeahead");
    t.typeahead({}, {'source': mySource});
});

For each dataset, there needs to be a source attribute that points to a function. That function takes the query string and a callback function. It is expected that you do what you need with the query string and then call the callback function with a list of objects where each object has an attribute of value that maps to the value to display.

I think you should be able to specify {'local': source} in the options, but I haven't gotten it to work.

Anyway, if you want the old API, you'll have to use Bootstrap 2's version of typeahead.

Upvotes: 1

Related Questions