0

I have a keydown event binding that is attached to elements which have the class numbersOnly which looks like this:

$('.numbersOnly').keydown(function(e) {
    // Determine which key was pressed and ignore if not a number.
});

This works on all elements which were added on page load. However, if I add the class to an element dynamically using .addClass(), the event does not fire on that element. I've tried changing .keydown( to .on('keydown', but it makes no difference (I know it shouldn't - they should be the same).

I'm using jQuery 1.9.1 but I've also tested this in 2.x and it doesn't work there either. Here's a fiddle with a working example:

http://jsfiddle.net/2L5cg/

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Joshua Whitley
  • 1,196
  • 7
  • 21

1 Answers1

2

You need to use delegated event as class is added dynamically:

$(document).on('click','.boxClick', function() {
    $('#displayText').show();
});

UPDATED FIDDLE

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160