-1

I'm creating a simple char counter for text area with jquery to limit the number of chars that a user can submit. I have setup a keyup event handler to catch the text change event. On IE, $(this).text().length perfectly. The event is fired and when I check the length of the textarea, I get a correct number. However, same thing doesn't work in FF/Chrome. The text().length always return zero (notice in the picture cnt = 0;) even though there are chars in the text area. The code and fiddler image is attached. Can someone see something that I'm doing wrong that makes it work in IE but not other top browsers? Thanks in advance.

 //for replying the post by viewers.  Limiting the number chars
$(document).on('keyup', '.txtareareply', function (b) {
    var cnt = $(this).text().length;
    var id = $(this).data("id");


    $("#charMaxCountReply" + id).html(cnt + " of 1000 Character Max.")
    if (cnt > 1000) {
        alert("You have reached the maximum number of characters allowed.");
        $(this).html($(this).text().substring(0, 1000));
        return;
    }

});

enter image description here

Zuzlx
  • 1,246
  • 14
  • 33
  • My guess would be .text isn't the right way to get a *value* from an input. – Kevin B Nov 24 '15 at 22:22
  • @KevinB Works on IE though. So should I try `val()` or `value` ? – Zuzlx Nov 24 '15 at 22:24
  • .val() is a method on jQuery objects, and .value is a property on the dom node. use whichever makes sense for what you have. (you have a jQuery object) – Kevin B Nov 24 '15 at 22:25
  • 1
    @KevinB Bah, saw your comment after I gave the answer. Sorry, should have let you use the constructive comment to make him think it through! – Trasiva Nov 24 '15 at 22:25
  • It worked! Thank you all. One thing I love about SO is that it always feels like you have a few million older brothers :) – Zuzlx Nov 24 '15 at 22:32

1 Answers1

0

Instead of using .text().length, use .val().length. This works on multiple controls, and will resolve your problem.

Trasiva
  • 494
  • 14
  • 29