开发者

Character counter for various textarea that are loaded dynamically, how to do it?

I've found a javascript code that counts the characters on a textarea. This is the code.

My problem is that I'm doing a backend where the user can load various textareas like <textarea name="description[]"></textarea>. How I can create a script that runs on all textareas BUT with different counts?

开发者_运维技巧

Thank you in advance!


This will allow you to just give text areas the class of countableText in order to add a counter to them.

  <script type='text/javascript'>
  $(window).load(function(){
    var characterLimit = 150;
    $('.countableText').each(function(index){
      $(this).wrap('<div id="container_' + (index+1) + '">');
      $('<span id="remainingCharacters_' + (index+1) + '">150</span>').appendTo($('#container_' + (index+1)));

      $(this).bind('keyup', function(){
        var charactersUsed = $(this).val().length;

        if(charactersUsed > characterLimit){
            charactersUsed = characterLimit;
            $(this).val($(this).val().substr(0,characterLimit));
            $(this).scrollTop($(this)[0].scrollHeight);
        }

        var charactersRemaining = characterLimit - charactersUsed;

        $('#remainingCharacters_' + (index+1)).html(charactersRemaining);
      })  
    }); 
  });
  </script>

  </head>
  <body>
    <textarea class="countableText"></textarea>  
    <textarea class="countableText"></textarea>  
    <textarea class="countableText"></textarea>    
  </body>
</html>

Here is a demo: http://jsfiddle.net/mEFGq/1/


If you are doing multiple counters you have to add the keyup property to your textarea and I choose a span for the result like in the following example:

<textarea id="myArea1" maxLength="100" onkeyup="javascript:updateCounter(this, "span1");" onkeypress="javascript:limitBox(this);"/>
<span id="span1"></span>

function limitBox(textbox) {
            if ($(textbox).val().length == $(textbox).attr("maxLength")) {
                return false;
            }

            if ($(textbox).val().length > $(textbox).attr("maxLength")) {
                var str = $(textbox).val().substring(0, $(textbox).attr("maxLength"));
                $(textbox).val(str);
            }

        }


function updateCounter(textbox, spanToUpdate) {
    if ($(textbox).val().length > $(textbox).attr("maxLength")) {
        var str = $(textbox).val().substring(0, $(textbox).attr("maxLength"));
        $(textbox).val(str);
    }

    var myCount = $(textbox).attr("maxLength") - $(textbox).val().length;

    $(spanToUpdate).html(myCount);


}

I also have max length properties on there. You can modify to remove if you don't need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜