Dynamically attach Typeahead to dynamically generated inputs

881 views Asked by At

I am dynamically creating input on witch I need to attach a twitter typeahead.

Since the html is dynamically generated server side and the input tag can only be selected from it's class, the only way I have found to attach it is by using the delegate() Jquery function.

In order to attach the typeahead only once to every input I am using the undelegate() function right after the delegate().

$(document).delegate(".receivers-input", "click", function () {
        console.log($(this)); // input.receivers-input.col-md-4.col-sm-4.col-xs-4
        $(this).undelegate($(this));
        $(this).typeahead({
            minLength: 0,
        }, {
            source: function (query, cb) {
                var Request = $.ajax({
                ...                     

This works well but I have this error message when I click on the attached typeahead :

Uncaught TypeError: Cannot read property 'origType' of undefined

This is probably because of $(this).undelegate($(this));

Does anyone knows how to prevent this error or have another way than delegate / undelegate to achieve my goal ?

1

There are 1 answers

1
Guillaume Beauvois On

Looks like I searched too far for function and haven't seen the simplest solution. I have achieve my goal by modifying the selector...

This is the code :

$(this).on("click", ".receivers-input:not(.tt-input)", function () {
        $(this).typeahead({
            minLength: 0,
        }, {

on binding works like delegate, it bind the handler to every existing or future element that match the selector.

Since typeahead add some data to the input it is attached to (tt-hint, tt-input, etc...), I just add in the selector :not witch exclude element with the typeahead classes.

Hope this might help someone, one day.