Tyler Wall
Tyler Wall

Reputation: 3788

Bootstrap Typeahead not working on dynamically added elements?

I am adding an input box via an onclick function - so the input box isn't there when the page render's and when document.ready() fires.

I came up with a work-around by adding a onclick function to the input field that calls a javascript function.

http://goo.gl/id6esq will returns json:

["1175-1234567890","1175-1234567891","1175-1234567892","1175-1234567893","1175-1234567894","1175-1234567895"]

(I couldn't get a jsfiddle working - won't do the typeahead)

<a id="clickbtn" class="btn-btn-inverse">Click me</a>

<div id="insert"></div>

<script type="text/javascript">
    $(function() {
        $('#clickbtn').on('click', function() {
            $('#insert').html("<input type='text' onclick='javascript:invoice_no_setup_typeahead($(this))' name='retrun-order-invoice_no' class='return-order-invoice_no' data-provide='typeahead'>");
        });
    });
    function invoice_no_setup_typeahead(self) {
        console.log('focus acheived');
        $(self).typeahead({
            source: function(query, process) {
                console.log(query);
                return $.get(
                        'http://goo.gl/id6esq', {
                    query: query
                },
                function(data) {
                    console.log(data);
                    return process(data);
                }, 'JSON');
            }
        });

    }
</script>

Upvotes: 1

Views: 1376

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Try

    $('#clickbtn').on('click', function() {
        var el = $("<input type='text' name='retrun-order-invoice_no' class='return-order-invoice_no'>").appendTo($('#insert').empty());
        invoice_no_setup_typeahead(el)
    });

Upvotes: 2

Related Questions