Q:

How to solve this simple jQuery issue?

I'm new to jQuery and JavaScript in general. I noticed that if you insert an element via jQuery into the DOM and try to perform an action on that element later, it fails. For example:
I am adding a class of "listenToField" to all the input elements on the page:
$(function() {

$('input').addClass('listenToField');

});

Then when I add the second function:
$(function() {

     $('input').addClass('listenToField');

     // second function
     $('.listenToField').keydown(function() {

          alert('Hi There')

     });

});

It does not alert 'Hi There'.
However if I hardcode the class "listenToField" into the HTML inputs, the alert works. How can I still have it work when jQuery inserts the class dynamically without resorting to hard coding?

A:

Try jQuery's live method.
The live() method assigns events to elements that exist, and ones that will be created.
http://api.jquery.com/live/
$('.listenToField').live('keydown', function() {
   alert('Hi there!');
})

A:

@jesus.tesh provides a correct workaround, but the reason this is not working as you expect can be found here.
Jquery only works on elements that exist when it is loaded.  You need to do further manipulation as explained in the FAQ if you need it work against elements that you create.

