-4

I want to have a text area which shows how much i wrote in it and displays it on the bottom right of the textarea(inside the textbox ) out of the max length of the value. cant find how to do so. Thanks.

Vera Gavriel
  • 381
  • 2
  • 5
  • 14

2 Answers2

1

You can achieve this using jQuery with the following simple code:

var theCounter = $('#textareaLength'),
    textarea = $('#myTextarea'),
    maxLength = textarea.attr('length');

theCounter.text('0 / '+maxLength);
theCounter.css({  
    'top': (textarea.offset().top + textarea.height()) - theCounter.height(),
    'left': (textarea.offset().left + textarea.width()) - theCounter.width()
});

textarea.on('keydown', function() {  
    var theLength = $(this).val().length;
    theCounter.text($(this).val().length+' / '+maxLength)
              .css({  
                  'left': (textarea.offset().left + textarea.width()) - theCounter.width()
              });
});

Obviously you'll need to put in some logic to prevent any further action from occuring if the max length is met, but that should be pretty self-explanatory.

I've put together a jsFiddle for you.

animuson
  • 53,861
  • 28
  • 137
  • 147
BenM
  • 52,573
  • 26
  • 113
  • 168
-1

Here is a function you can use

JAVASCRIPT:

function CountWords(s) {
   var maxChars = 2048;
   if (s.value.length > maxChars) {
       s.value = s.value.substring(0, maxChars);
   }
   else {
       $($(s).parent()).find("#words").html((maxChars - s.value.length) + " characters     left.");
   }
}

HTML:

<textarea onkeyup="CountWords(this)" id="txtBody" rows="50" cols="10"
            ></textarea>
        <span id="words" style="width: 120px; color:Gray; display: block; float: left; margin: 5px; line-height: 27px;">
            2048 characters left.</span>

you can just change the numbers to how many letter limit you want.

Jeandre Pentz
  • 992
  • 2
  • 9
  • 20
  • 1
    You're using a combination of vanilla JavaScript and jQuery in your answer - it might be worth mentioning that. Also, it's 2013; please don't recommend intrusive event handlers. – BenM Jul 18 '13 at 10:25