Reputation: 63
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
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
Reputation: 19678
Try jQuery's live
method.
The live()
method assigns events to elements that exist, and ones that will be created.
$('.listenToField').live('keydown', function() {
alert('Hi there!');
})
Upvotes: 3
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
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