Jean-Philippe Murray Jean-Philippe Murray - 1 year ago 80
jQuery Question

Bind on(keyup) to dynamic elements in jQuery (Twitter Bootstrap + typehead)

I guess some of you must have frowned eyebrows reading this title eh ? I'm sure people asks this everytime, yet, I haven't seen my particular question around so, I'm trying ! Binding events to dynamically created elements is my kryptonite, I just can't wrap my head around it ...

So ok, I'm using Twitter Boostrap, with the typehead() plugin. I'm using this trick to make it work with remote sources of data. At this point, everything work. I click on a text input in my form, tagged for it, and the scripts go load external sources and the drop down appears. But I have dynamic element creation, and you've figured, it just won't work on them. I was exploring the live() method, but looking at "how" the scripts is getting fired, I'm just not sure how I can implement it.

$('#anInputField').typeahead().on('keyup', function(ev){
// stuff happens

Everytime there is a keyup, the script fires a jSON request, checks his things, and gets the result back to typehead() who does the autocomplete part of the job. So how can I say to jQuery to look at #aDropdownID created after the initial binding? I went on and checked if I could use live(), but since on() replaces it... I'm clueless !

Any help appreciated !

EDIT : I've removed the checkmark on the solution, given it's been shuned my the community.

Answer Source

For on() to be able to delegate you have to call it on a static element that you know is always going to be there and then you pass the dynamic element like:

$('#static-parent').on('keyup', '#aDropdownID', function(ev){
 // stuff happens

If you don't have a static parent element, then you can always use body.