Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 every time, 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
});

Every time 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 !

like image 926
Jean-Philippe Murray Avatar asked Mar 18 '12 20:03

Jean-Philippe Murray


2 Answers

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.

like image 105
elclanrs Avatar answered Sep 17 '22 16:09

elclanrs


This works for me:

$(document).on('keyup', '#YourInputFieldId', function () {
    //stuff happens
});
like image 26
Mark Ryan Orosa Avatar answered Sep 18 '22 16:09

Mark Ryan Orosa