0

I have the following function that counts the number of characters left the user has to type in a textarea:

$("textarea").keyup(function() {
    var max = 500;
    var length = $(this).val().length;
    var char = max - length;
    if (length > max) {
        $(this).parent().find('.counter span').html('<div class="text-error">' + char + '</div>');
    } else {
        $(this).parent().find('.counter span').text(char);
    }
});

If I introduce a new DOM to the page, the above function doesn't work for the newly introduced textarea. How can I make it work with new DOMs?

Thanks.

Bagwell
  • 2,018
  • 5
  • 18
  • 24

2 Answers2

6

You want the on function in jQuery.

$("body").on("keyup", "textarea" , function() { ...

http://api.jquery.com/on/

MattDiamant
  • 8,561
  • 4
  • 37
  • 46
2

MattDiamant's answer is good for your situation but I would just like to add about the situation of a Copy-Paste.

If the user copies from another word document and pastes it in the keyarea using the Mouse only(Right-click -> Paste), the keyup wont be triggered.

So, in addition to 'keyup', I would advice you to add the events 'input', 'propertychange', so your onfunction will be:

$("body").on('keyup input propertychange', 'textarea', function() { ... });

Zeblimiski
  • 116
  • 1
  • 6