George
George

Reputation: 63

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?

Upvotes: 5

Views: 88

Answers (4)

Jarrett Meyer
Jarrett Meyer

Reputation: 19583

Another thought, why take two steps? jQuery is chainable. The return value of a jQuery function is the jQuery object.

$("input").addClass("listenToField").keydown(function () { alert("Hi There"); });

Don't go too overboard with this. When jQuery chains get too long, they become difficult to read.

Upvotes: 0

Felipe Buccioni
Felipe Buccioni

Reputation: 19678

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!');
})

Upvotes: 3

ChrisW
ChrisW

Reputation: 9409

@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.

Upvotes: 3

Tim Hobbs
Tim Hobbs

Reputation: 2017

Just cut out the middleman:

(function() {
     $('input').keydown(function() {
          alert('Hi There')
     });
});

You are applying the class to all inputs anyway, so just attach the keydown event instead. You can still apply the class if you need it for CSS styling too.

Upvotes: 1

Related Questions