palintropos
palintropos

Reputation: 13

Twitter typeahead.js breaks when cloned with jQuery clone() [fiddle inside]

I have been integrating Twitter typeahead.js (version 0.9.2) into a project of mine with great success, but I ran into a problem the other day on a page that uses jQuery's clone() method to insert and remove form controls.

Here's a fiddle showing what I mean. Try typing 'o' or 't' into the existing element, then adding a new one with the '+' or '>>' buttons. If you then click on the newly created typeahead, you can see that it opens the suggestions menu for the one above it, and otherwise doesn't act like a typeahead at all.


Here's part of the fiddle since SO won't let me post just a link:

HTML Dom structure surrounding typeahead

<div class="outer">
<div class="inner">
    <form>
        <input name="example" /> <!-- initialized as typeahead -->
        <button type="button" class="addBlock">+</button>
        <!-- other buttons omitted -->
    </form>
</div>
</div>

jQuery driver code for '+' button

$(document).on('click', '.addBlock', function(){
    var clone = $(this).parents('.inner').clone(true, true);
    clone.appendTo($('div.outer'));
});

Upvotes: 1

Views: 706

Answers (1)

Kevin Kulla
Kevin Kulla

Reputation: 460

It's because you are only calling the typeahead function when the page is ready. The element that you're creating doesn't exist at device ready so typeahead isn't getting assigned to it. you have to call typeahead every time that you add a new one.

Upvotes: 1

Related Questions