jquerytwitter-bootstraptypeaheadbootstrap-typeaheadjquery-events

tcrosen typeahead plugin is not functioning on dynamically created input


I am using tcrosen typeahead plugin and it's working fine when I use it on static input, but when using it on dynamically created input the plugin isn't executed well. I tried to debug my code using firebug and I noticed that the options are not taken !

This is how I use it :

    function displayResult(item, val, text) {
       console.log(item);
       $('.alert').show().html('You selected <strong>' + val + '</strong>: <strong>' + text + '</strong>');
    }
    $('.typeahead-input').typeahead({
       ajax: { url: 'carsController.php?method=searchNames', triggerLength: 1 }, 
       itemSelected: displayResult
    });

this is the code that get the dynamic input:

    $("#add-typeahead").click(function(){
       $.ajax({url:"ajaxController.php?method=typeahead",success:function(data){
        $("body").append(data);
       });
    });

HTML :

     <button id="add-typeahead">add typeahead</button><br>

Result of ajax call triggered by the button:

    <input type="text" class="typeahead-input"  data-provide="typeahead" />

Notice that inputs having class=".typeahead-input" are created by ajax call triggered by the button . Any help?


Solution

  • You need to place the typeahead init code in the success callback of the first ajax, it should be done after the input is added, so after append(). Since append() is sync and it doesn't provide a callback, you can use each() to workaround. So it would be something like this:

    $("#add-typeahead").click(function(){
        $.ajax({url:"ajaxController.php?method=typeahead",success:function(data){
            $("body").append(data).each(function () {
                function displayResult(item, val, text) {
                   console.log(item);
                   $('.alert').show().html('You selected <strong>' + val + '</strong>: <strong>' + text + '</strong>');
                }
    
                $('.typeahead-input').typeahead({
                   ajax: { url: 'carsController.php?method=searchNames', triggerLength: 1 }, 
                   itemSelected: displayResult
                });
            });
        });
    });
    

    Hope it helps.