4

i'm using twitter bootstrap 2.0.4. i want to populate the dropdown using ajax. the source property of the typeahead plugin requires the value of source to be either an array or a function. i tried changing the value of the array after the ajax request but it only displays the results of the first request.

<form class="navbar-search">
   <input type="text" id="searchSong" class="typeahead" placeholder="Search">
</form>

 $('.typeahead').keyup(function(){                     
                var list;
                var q = $('.typeahead').val();
                if(!q){
                    return;
                }
                $.ajax({
                    type: "GET",
                    url: "/WebApplication1/Playlist/search?query="+q,
                    success: function(data){
                        list = data.split(',');
                        alert(list);
                        $('.typeahead').typeahead({
                            source: list
                        })
                    }
                });

the alert box shows the data loaded from ajax is correct but the dropdown still shows the previous values

Akshay Takkar
  • 500
  • 1
  • 7
  • 21

4 Answers4

3

You can't re-initialize the plugin if it's already in use.

Try updating the already at work typeahead : Live demo (jsfiddle)

var typeahead = $('.typeahead').data('typeahead');
if(typeahead) typeahead.source = list;
else $('.typeahead').typeahead({source: list});

Plugin code responsible (github)

Sherbrow
  • 17,279
  • 3
  • 64
  • 77
  • this doesn't work, it returns 'm getting Cannot set property 'source' of undefined – daniel.sedlacek Jul 18 '14 at 14:13
  • @daniel.sedlacek As you can see in the demo, it works with v2. You might be using Bootstrap v3 : if so, the typeahead plugin has been removed in favor of [typeahead.js](https://github.com/twitter/typeahead.js) – Sherbrow Jul 19 '14 at 14:46
1

I don't think that version supports populating typeahead with ajax out-of-the-box. There are versions of the plugin, though, that do support it.

Here's one. I don't remember if that's the same one I'm using, but if it is, it works very well. I'll find out for sure and update this answer.

Update:

Here is a question you should look at. This extension given in the selected answer is the one I use.

Community
  • 1
  • 1
qxn
  • 17,162
  • 3
  • 49
  • 72
0

This has an answer here.

Update or change typeahead data

The way to do this is to use a BloodHound as a source. Whatever the data, remote or local, it is the only way I found to update the source dynamically.

None of the syntax above worked for me but that could be because my typehead search uses multiple sources.

pasx
  • 2,718
  • 1
  • 34
  • 26
-3

Eat this

  $.get('/my_url/' + some_params, function(data){
    $("#address-field").typeahead().data().typeahead.source = data
  },'json');
John Smith
  • 61
  • 3