I have a list of inputs and when the user enters a specific key, something happens. This works great but there is also a button to fetch content from a server (JSON) and then add it to the dom (HTML) after it has been formatted (Markup.js). The problem is that on the inputs that are injected after the dom is loaded the keyup events do not register. What is causing this problem?
Asked
Active
Viewed 678 times
1
-
3`$(staticElement).on('event', 'dynamicElement', function(){ //code here});` – Ohgodwhy May 07 '13 at 02:00
2 Answers
2
Use .on()
instead of .bind()
.
For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs.
See jQuery - how to use the "on()" method instead of "live()"? on how to use .on()
, and https://stackoverflow.com/a/14354091/584192 for examples on how to migrate existing code.

Community
- 1
- 1

Samuel Liew
- 76,741
- 107
- 159
- 260
-
The problem is because of `event delegation` and not using of .bind() instead of .on() .. Even though using the latter is a better practice. – Sushanth -- May 07 '13 at 02:14
-
The problem is that when I use like $('body').on('keyup', obj, func...) the second argument needs to be a jquery object and then it only works on current and not ones that will be inject later? – Jason Silberman May 07 '13 at 03:35
-
It will only work on the ones that already are injected... Let me try again in the morning – Jason Silberman May 07 '13 at 07:01
0
You must to bind the events AFTER the injection of the inputs. Can you post you're relevant code to better answer this question?

Marco Muciño
- 620
- 2
- 9
- 19