How do I add typeahead dynamically and get the id of the input element?

I am using typeahead.js and am running into problems. I have this html.

<input class="typeahead" type="text" id="element_1" >
<input class="typeahead" type="text" id="element_2" >

      

And I create similar input elements dynamically. If I use the code below, it works for initial input elements, but not for dynamically created elements, which is correct.

$('.typeahead').each(function() {
    $(this).typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    }, {
        name: 'items',
        displayKey: 'value',
        source: populateItems(this.id)
    })
});


function populateItems (id) {
    return function findMatches(inp, cb) {
        console.log("id: " + id);  //this is where i am accessing id
    };
};

      

If anyone can help me how should I use this so that the typeahead can be registered for all dynamically created elements and at the same time I can get the id of the active element.

+3


source to share





All Articles