I have seen a bunch of questions on this but im still stumped. I could realy use some help understanding what im doing wrong here.
(my terminology may not be correct below)
I have a textarea and a .keyup function bound to it by class name
This first textarea fires the function fine
I then add a second textarea dynamically which is intended to fire the same function
My .keyup function
$('.trans').keyup(function() {
alert("Working");
});
I understand that the above doesnt work on the newly created textarea because it wasnt part of the DOM when the function was bound. I have tried several ansers to other questions but cant seem to get this working:
Other things Ive tried:
// I also tried this
// Neither textarea responds if this is used
$('.trans').on('keyup', '.newTrans', function() {
alert("Working");
});
// I also tried this
// Only the first textarea responds
$('.trans').delegate('.newTrans', 'keyup', function(){
alert("Working");
});
Here is a JSfiddle with more of the code im using if needed:
The .on()
method isn't going to work in your fiddle at all because you have specified an old version of jQuery from before .on()
was introduced.
If you upgrade to a newer version of jQuery (at least 1.7) you can do this:
$(document).on('keyup', '.trans', function() {
alert("Working");
});
Demo: http://jsfiddle.net/VFt6X/4/
If you need to keep using v1.6.4 for some reason then use the .delegate()
method instead:
$(document).delegate('.trans', 'keyup', function() {
alert("Working");
});
Demo: http://jsfiddle.net/VFt6X/5/
Note that either way the '.trans'
selector for the elements you care about is passed as a parameter to the function. The $(...)
part on the left has to specify some container that already exists. I've used document
, but it is better to specify something closer to the elements in question if possible, so in your case you could use $("#centerNotes")
.