There is a form:

<textarea id="textarea" maxlength="25"></textarea><div id="textareaFeedback"></div> 

And a script that displays how many characters are left:

 <script> $(function() { var maxLength = $('#textarea').attr('maxlength'); $('#textarea').keyup(function() { var curLength = $('#textarea').val().length; $(this).val($(this).val().substr(0, maxLength)); var remaning = maxLength - curLength; if (remaning < 0) remaning = 0; $('#textareaFeedback').html(remaning + ' осталось символов'); if (remaning < 10) // когда менять цвет { $('#textareaFeedback').addClass('warning') } else { $('#textareaFeedback').removeClass('warning') } }) }) </script> 

How to make the number of characters displayed immediately, and not after the start of printing on the form?

  • Initially, 0 characters? So write down the maximum number in the output block - Deonis
  • Not necessarily zero. The fact is that the text from the database is displayed in the field. - Frontender

1 answer 1

If there are options that the field is not initially empty, then just at the very beginning, we check how many characters there are and subtract this number from the maximum allowed. Primerchik .

PS ( advice on the go ) Your code would be good to optimize.

  • Well, the fact is that the field is initially empty. And then after filling it is used for editing. - Frontender
  • Something you completely confused me. Have you tried my version in action? Let it be empty, who against? In this case there will be a maximum number of characters. - Deonis
  • Yes, I have confused myself already. Thanks for the help. This is what you need. - Frontender